vue+websocket demo:
node 服务端启websocket服务:
// 导入WebSocket模块: const WebSocket = require('ws'); // 引用Server类: const WebSocketServer = WebSocket.Server; // 实例化: const wss = new WebSocketServer({ port: 8081 }); wss.on('connection', function (ws) { console.log(`[SERVER] connection()`); ws.on('message', function (message) { console.log(`[SERVER] Received: ${message}`); ws.send(`ECHO: ${message}`, (err) => { if (err) { console.log(`[SERVER] error: ${err}`); } }); }) });
运行前后端代码:
前端页面可以看到发送websocket数据后,接收到了后端的数据,实现了双向通信。
更新:2021.14
服务端群发消息:
// 导入WebSocket模块: const WebSocket = require('ws'); const wss = new WebSocket.Server({ port: 8081 }); wss.on('connection', function connection(ws) { ws.on('message', function incoming(data) { wss.clients.forEach(function each(client) { if (client !== ws && client.readyState === WebSocket.OPEN) { client.send(data); } }); }); });
作者:孟繁贵