不同的WebSocket连接但接收到的消息混杂在一起”
创始人
2025-01-08 20:00:31
0

在服务器端为每个WebSocket连接创建一个唯一标识符,并在每条发送的消息中包含此标识符。客户端收到消息后,可以根据标识符将它们分组并正确地显示。以下是Node.js示例代码:

// server side const WebSocket = require('ws'); const wss = new WebSocket.Server({ port: 8080 });

function getUniqueID() { return Date.now().toString(36) + Math.random().toString(36).substr(2); }

wss.on('connection', function connection(ws) { const uniqueID = getUniqueID(); ws.id = uniqueID;

ws.on('message', function incoming(message) { const parsedMsg = JSON.parse(message); const sendMsg = { id: ws.id, content: parsedMsg.content, };

wss.clients.forEach(function each(client) {
  if (client.readyState === WebSocket.OPEN && client.id !== ws.id) {
    client.send(JSON.stringify(sendMsg));
  }
});

}); });

// client side const socket = new WebSocket('ws://localhost:8080');

socket.addEventListener('message', function(event) { const parsedMsg = JSON.parse(event.data); const messageDiv = document.createElement('div'); messageDiv.innerText = parsedMsg.content; document.body.appendChild(messageDiv); });

相关内容

热门资讯

近日"hhpoker... 近日"hhpoker辅助器"德普之星怎么设置埋牌(总是真的有辅助神器)-哔哩哔哩1、完成德普之星怎么...
最终"wepoker... 最终"wepoker怎么开辅助"pokemmo内置修改器(竟然是有辅助软件)-哔哩哔哩1、进入游戏-...
透视辅助"wepok... 透视辅助"wepoker软件安装包"wepoker免费脚本咨询(本来存在有辅助辅助器)-哔哩哔哩一、...
据公告内容"wepo... 据公告内容"wepoker的辅助器"epoker透视(原来是有辅助神器)-哔哩哔哩1、进入游戏-大厅...
透视有挂"wepok... 透视有挂"wepoker免费钻石"wpk辅助器是真的吗(都是真的是有辅助软件)-哔哩哔哩1、下载好w...
这一问题亟待解决"约... 这一问题亟待解决"约局吧德州有挂吗"佛手在线大菠萝辅助(竟然有辅助插件)-哔哩哔哩1、下载好佛手在线...
据了解"wepoke... 据了解"wepoker有人用过吗"红龙poker辅助(果然存在有辅助神器)-哔哩哔哩1、操作简单,无...
近日"wepoker... 近日"wepoker透视脚本是什么"werplan脚本(都是真的是有辅助工具)-哔哩哔哩;1、该软件...
透视脚本"德州hhp... 透视脚本"德州hhpoker是真的吗"红龙poker辅助工具(确实存在有辅助app)-哔哩哔哩1、金...
最终"uupoker... 最终"uupoker有透视吗"xpoker辅助控制(原来是有辅助下载)-哔哩哔哩uupoker有透视...