時間:2023-07-22 10:33:01 | 來源:網(wǎng)站運營
時間:2023-07-22 10:33:01 來源:網(wǎng)站運營
一步一步教您用websocket+nodeJS搭建簡易聊天室(1):WebSocket是HTML5開始提供的一種在單個 TCP 連接上進行全雙工通訊的協(xié)議。var Socket = new WebSocket(url, [protocol] );
以上代碼中的第一個參數(shù) url, 指定連接的 URL。第二個參數(shù) protocol 是可選的,指定了可接受的子協(xié)議。<!doctype html><html> <head> <meta charset="utf-8"> <title>websocket</title> </head> <body> <h1>echo test</h1> <input id="sendText" type="text" /> <button id="sendBtn">發(fā)送</button> <div id="recv"></div> </body> <script type="text/javascript"> /* 本樣例實現(xiàn)功能: 點擊發(fā)送按鈕獲取文本框的內(nèi)容并將它發(fā)送到服務(wù)端, 服務(wù)端將這條消息原樣返回并顯示在頁面。 為了便于新手理解,服務(wù)端接口使用websocket官方服務(wù) */ var websocket=new WebSocket("ws://echo.websocket.org/");//創(chuàng)建一個websocket連接,服務(wù)端使用websocket官方服務(wù) websocket.onopen=function(){ //websocket服務(wù)打開 console.log("websocket open"); document.getElementById("recv").innerHTML="connected"; } websocket.onclose=function(){ //websocket服務(wù)關(guān)閉 console.log("websocket close"); } websocket.onmessage=function(e){ //websocket服務(wù)接收到消息 console.log(e.data); document.getElementById("recv").innerHTML=e.data;//將消息顯示在消息列表 } document.getElementById("sendBtn").onclick=function(){ var txt=document.getElementById("sendText").value; websocket.send(txt);//將文本輸入框中的內(nèi)容發(fā)送到服務(wù)端 } </script></html>
運行截圖:關(guān)鍵詞:簡易
微信公眾號
版權(quán)所有? 億企邦 1997-2025 保留一切法律許可權(quán)利。