服务器代码 ( 依赖于 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); } }); });
前端代码 ( 该页面可同时打开多个进行聊天 )
<!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" /> </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); } </script> </html>
时间: 2024-10-23 16:22:49