node + h5 + websocket + koa2 實現簡單的多人聊天


服務器代碼  ( 依賴於 koa2,  koa-websocket )

/* 實例化外部依賴 */ let Koa = require("koa2"); let WebSocket = require("koa-websocket"); /* 實例化 WebSocket, 實例化儲存所有上線文數組 並分配監聽的端口 */ let app = WebSocket(new Koa()); let ctxs = []; app.listen(80); /* 實現簡單的接發消息 */ app.ws.use((ctx, next) => { /* 每打開一個連接就往 上線文數組中 添加一個上下文 */ ctxs.push(ctx); ctx.websocket.on("message", (message) => { console.log(message); for(let i = 0; i < ctxs.length; i++) { if (ctx == ctxs[i]) continue; ctxs[i].websocket.send(message); } }); ctx.websocket.on("close", (message) => { /* 連接關閉時, 清理 上下文數組, 防止報錯 */ let index = ctxs.indexOf(ctx); ctxs.splice(index, 1); }); });

前端代碼 ( 該頁面可同時打開多個進行聊天 )

<!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <title>Title</title> </head> <body> <input type="text" id="content" /> <input type="button" value="發送" id="send" /> <input type="button" value="關閉" id="close" /> </body> <script type="text/javascript"> /* 封裝 WebSocket 實例化的方法 */ var CreateWebSocket = (function () { return function (urlValue) { if(window.WebSocket) return new WebSocket(urlValue); if(window.MozWebSocket) return new MozWebSocket(urlValue); return false; } })(); /* 實例化 WebSocket 連接對象, 地址為 ws 協議 */ var webSocket = CreateWebSocket("ws://localhost"); /* 接收到服務端的消息時 */ webSocket.onmessage = function (msg) { console.log("服務端說:" + msg.data); }; /* 關閉時 */ webSocket.onclose = function () { console.log("關閉連接"); }; /* 發送消息 */ document.getElementById("send").onclick = function () { var str = document.getElementById("content").value; webSocket.send(str); } /* 關閉消息 */ document.getElementById("close").addEventListener("click", function () { webSocket.close(); }); </script> </html>

 

 


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM