xxg0 2018-11-28
1、首先安装好nodejs-websocket
npm install nodejs-websocket --save -g
2、编写服务端
var ws = require("nodejs-websocket") var AllUserData = new Array() // Scream server example: "hi" -> "HI!!!" var server = ws.createServer(function (conn) { console.log("New connection") conn.on("text", function (str) { console.log("Received "+str) AllUserData.push({ 'id':str, 'ws':conn }) conn.sendText(str.toUpperCase()+"!!!") }) conn.on("close", function (code, reason) { console.log("Connection closed") // 当用户退出的时候捕捉到退出的用户 for (var i=0 in AllUserData) { if (AllUserData[i].ws == conn) { console.log(AllUserData[i]) } } }) }).listen(8001)
3、简易客户端
<!DOCTYPE html> <html> <head> <title>django-websocket</title> <script src="http://code.jquery.com/jquery-1.11.1.min.js"></script> <script type="text/javascript">//<![CDATA[ $(function () { $('#connect_websocket').click(function () { if (window.s) { window.s.close() } /*创建socket连接*/ var socket = new WebSocket("ws://127.0.0.1:8001"); socket.onopen = function () { console.log('WebSocket open');//成功连接上Websocket }; socket.onmessage = function (e) { console.log('message: ' + e.data);//打印出服务端返回过来的数据 $('#messagecontainer').prepend('<p>' + e.data + '</p>'); }; // Call onopen directly if socket is already open if (socket.readyState == WebSocket.OPEN) socket.onopen(); window.s = socket; }); $('#send_message').click(function () { //如果未连接到websocket if (!window.s) { alert("websocket未连接."); } else { window.s.send($('#message').val());//通过websocket发送数据 } }); $('#close_websocket').click(function () { if (window.s) { window.s.close();//关闭websocket console.log('websocket已关闭'); } }); }); //]]></script> </head> <body> <br> <input type="text" id="message" value="user1"/> <button type="button" id="connect_websocket">连接 websocket</button> <button type="button" id="send_message">发送 message</button> <button type="button" id="close_websocket">关闭 websocket</button> <h1>Received Messages</h1> <div id="messagecontainer"> </div> </body> </html>
总结