Socket.io通过id获取套接字无法正常工作

时间:2016-04-04 16:08:43

标签: node.js socket.io

我正在尝试通过其ID访问套接字。我看过documentationthis stackoverflow帖子。然而,

io.sockets.connected[socket.id]

返回undefined。

这也不起作用:

io.to(socket.id).emit("myMessage");

Socket连接到命名空间(socket.id返回/ playNS#1HhBtUM-6O_YsRwmAAAF),socket.io版本是1.4.5。我做错了什么?

1 个答案:

答案 0 :(得分:2)

If a socket is connected to a namespace, the first part of socket.id contains that namespace (e.g. /playNS#1HhBtUM-6O_YsRwmAAAF) , but io.sockets.connected property for that socket would be /#1HhBtUM-6O_YsRwmAAAF

In order to properly retrieve the socket I used io.of('/namespace').connected[socket.id].

Similarly, io.of("/namespace").to(socket.id).emit("myMessage"); to send a message