简体   繁体   中英

Socket.io get socket by id not working

I am trying to access a socket by its id. I have seen this and this stackoverflow posts. However,

io.sockets.connected[socket.id]

returns undefined.

This also doesn't work :

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

Socket is connected to a namespace (socket.id returns /playNS#1HhBtUM-6O_YsRwmAAAF) and socket.io version is 1.4.5. What am I doing wrong?

If a socket is connected to a namespace, the first part of socket.id contains that namespace (eg /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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM