nodejs-websocket是nodejs的websocket模块
服务端:
var ws = require(‘nodejs-websocket‘); var wsPort = 3000; var peers = []; var server = ws.createServer(function(conn){ peers.push(conn); // 事件名称为text(读取字符串时,就叫做text),读取客户端传来的字符串 var count = 1; conn.on(‘text‘, function(str) { // 在控制台输出前端传来的消息 console.log(str); //向前端回复消息 //conn.sendText(‘服务器端收到客户端端发来的消息了!‘ + count++); //群发 for(let i=0,len=peers.length;i<len;i++){ if(peers[i]!=conn){ peers[i].sendText(‘转发客户端的消息:‘+str); } } }); conn.on(‘close‘,(code, reason)=>{ console.log("Connection closed") }); conn.on("error", function (code, reason) { console.log("异常关闭") }); }); server.listen(wsPort,‘0.0.0.0‘,()=>{ console.log(‘websocket服务启动-使用端口‘,wsPort); });
客户端:
<!DOCTYPE html> <html> <head> <meta charset="utf-8"> <title></title> </head> <body> url:<input id="url" value="ws://127.0.0.1:3000/"/> <button onclick="svc_connectPlatform()"> connect</button><br/> <br/> <input id="msg" /> <button id="sendbtn"> send</button> <script> var url = document.getElementById("url"); var sendbtn = document.getElementById("sendbtn"); var inputmsg = document.getElementById("msg"); sendbtn.onclick = function(){ svc_send(inputmsg.value); } function svc_connectPlatform() { //alert(""); var wsServer = url.value.trim(); try { svc_websocket = new WebSocket(wsServer); } catch (evt) { console.log("new WebSocket error:" + evt.data); svc_websocket = null; if (typeof(connCb) != "undefined" && connCb != null) connCb("-1", "connect error!"); return; } //alert(""); svc_websocket.onopen = svc_onOpen; svc_websocket.onclose = svc_onClose; svc_websocket.onmessage = svc_onMessage; svc_websocket.onerror = svc_onError; } function svc_onOpen(evt) { console.log("Connected to WebSocket server."); } function svc_onClose(evt) { console.log("Disconnected"); } function svc_onMessage(evt) { console.log(‘Retrieved data from server: ‘ + evt.data); } function svc_onError(evt) { console.log(‘Error occured: ‘ + evt.data); } function svc_send(msg) { if (svc_websocket.readyState == WebSocket.OPEN) { svc_websocket.send(msg); } else { console.log("send failed. websocket not open. please check."); } } </script> </body> </html>