nodejs 使用nodejs-websocket模組實現點對點實時通訊
阿新 • • 發佈:2018-11-25
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>