【发布时间】:2017-06-09 19:01:59
【问题描述】:
我的问题是,我目前使用带有 node.js 的库“ws”发送特定套接字的解决方案还不够好。
原因是因为如果我使用客户端定义的相同用户 ID 使用多个选项卡连接到 websocket 服务器,它只会引用指定用户 ID 的最新连接。
这是我的代码:
// Server libraries and configuration
var server = require("ws").Server;
var s = new server({ port: 5001});
// An array which I keep all websockets clients
var search = {};
s.on("connection", function(ws, req) {
ws.on("message", function(message){
// Here the server process the user information given from the client
message = JSON.parse(message);
if(message.type == "userinfo"){
ws.personName = message.data;
ws.id = message.id;
// Defining variable pointing to the unique socket
search[ws.id] = ws;
return;
}
})
})
如您所见,每次连接相同 id 的套接字时,都会引用最新的。
例子如果你不明白:
- 客户端连接到 ID 为 1337 的服务器
- search[1337] 定义为 --> websocket 1
- 具有相同 ID 的新连接:1337
- search[1337] 改为引用 websocket 2 的变量
【问题讨论】:
-
显然会发生,你为什么要覆盖socket id?将所有套接字 ID 保存在一个数组中,供 1 个用户使用。
-
您能详细说明一下吗?所以你的意思是我应该为每个包含套接字连接的用户 ID 创建一个数组?
-
是的,我基本上使用有房间的socket.io。所以它变得更容易了。我从来没有
ws,但这可以解决您的问题。
标签: javascript node.js websocket