您好,登錄后才能下訂單哦!
1、首先安裝好nodejs-websocket
npm install nodejs-websocket --save -g
2、編寫服務(wù)端
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") // 當(dāng)用戶退出的時(shí)候捕捉到退出的用戶 for (var i=0 in AllUserData) { if (AllUserData[i].ws == conn) { console.log(AllUserData[i]) } } }) }).listen(8001)
3、簡(jiǎn)易客戶端
<!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() } /*創(chuàng)建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);//打印出服務(wù)端返回過來的數(shù)據(jù) $('#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發(fā)送數(shù)據(jù) } }); $('#close_websocket').click(function () { if (window.s) { window.s.close();//關(guān)閉websocket console.log('websocket已關(guān)閉'); } }); }); //]]></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">發(fā)送 message</button> <button type="button" id="close_websocket">關(guān)閉 websocket</button> <h2>Received Messages</h2> <div id="messagecontainer"> </div> </body> </html>
總結(jié)
以上所述是小編給大家介紹的nodejs 使用nodejs-websocket模塊實(shí)現(xiàn)點(diǎn)對(duì)點(diǎn)實(shí)時(shí)通訊,希望對(duì)大家有所幫助,如果大家有任何疑問請(qǐng)給我留言,小編會(huì)及時(shí)回復(fù)大家的。在此也非常感謝大家對(duì)億速云網(wǎng)站的支持!
免責(zé)聲明:本站發(fā)布的內(nèi)容(圖片、視頻和文字)以原創(chuàng)、轉(zhuǎn)載和分享為主,文章觀點(diǎn)不代表本網(wǎng)站立場(chǎng),如果涉及侵權(quán)請(qǐng)聯(lián)系站長(zhǎng)郵箱:is@yisu.com進(jìn)行舉報(bào),并提供相關(guān)證據(jù),一經(jīng)查實(shí),將立刻刪除涉嫌侵權(quán)內(nèi)容。