node搭建websocket 服务
1.node安装websocket.
node安装目录下执行 npm install nodejs-websocket
2.新建JS文件 server.js
1 //server.js 2 var ws = require("nodejs-websocket") 3 var port = 8888; 4 //createServer 5 var server = ws.createServer(function (conn) { 6 conn.on("text", function (str) { 7 console.log("received " + str); 8 //send msg 9 conn.sendText(str); 10 }); 11 12 conn.on("close", function (code, reason) { 13 console.log("Connection closed") 14 }); 15 16 conn.on("error", function (err) { 17 console.log("handdle error"); 18 console.log(err); 19 }) 20 }).listen(port); 21 console.log("websocket server listening on port " + port);
2.1运行server.js node server.js
3.新建html文件
1 <!DOCTYPE html> 2 <html lang="en"> 3 <head> 4 <meta charset="UTF-8"> 5 <meta name="viewport" content="width=device-width, initial-scale=1.0"> 6 <title>Node-Websocket</title> 7 </head> 8 <body> 9 <input type="button" id = "send" value="发送"> 10 <input type="button" id = "close" value="关闭连接"> 11 <div id="msg"></div> 12 </body> 13 <script> 14 var ws = new WebSocket("ws://localhost:8888"); 15 ws.onopen = function(e) 16 { 17 console.log("connect..."); 18 } 19 20 ws.onmessage = function(e) 21 { 22 document.getElementById("msg").innerHTML = e.data; 23 console.log("send message"); 24 } 25 26 ws.onclose = function() 27 { 28 console.log("close connect!"); 29 } 30 31 ws.onerror = function() 32 { 33 console.log("socket error..."); 34 } 35 36 document.getElementById("send").onclick = function() 37 { 38 ws.send("send message..."); 39 } 40 41 document.getElementById("close").onclick = function() 42 { 43 ws.close(); 44 } 45 46 </script> 47 </html>
4.直接在浏览器运行html
原文:https://zhuanlan.zhihu.com/p/31003484