Socket.IO 1.0.x:通过id获取套接字

Dũn*_*yễn 15 node.js socket.io socket.io-1.0

在0.9.x版本中,我们可以通过ID获取套接字,如下所示:

io.sockets.socket(socketId)
Run Code Online (Sandbox Code Playgroud)

但在1.0.x我们不能.如何在1.0.x中通过id查找套接字?

Sar*_*ita 37

对于socket.io 1.0使用:

io.sockets.connected[socketId]
Run Code Online (Sandbox Code Playgroud)

对于0.9,它的io.sockets.sockets [socketId]而不是io.sockets.socket [socketId]

  • 对于命名空间连接,我无法通过 `io.sockets.connected[socketId].emit()` 访问它,但它的工作方式类似 `var nsp = io.of('/my-namespace');` 然后是 `nsp.connected [socketId].emit()`。谢谢 (2认同)

小智 16

你也可以使用:

io.to(socketid).emit();
Run Code Online (Sandbox Code Playgroud)


小智 9

Socket.io 版本 4.0.0

io.sockets.sockets.get(socketId);


isa*_*123 7

版本 3.0.3

// in "of", you can put '/' or whatever namespace you're using
    
io.of('/').sockets.get(socketId)
Run Code Online (Sandbox Code Playgroud)

基本上,sockets不再是简单的Object。这是一个 Map,所以你必须使用.get().


par*_*les 6

Socket.io版本2.0.3+

    let namespace = null;
    let ns = _io.of(namespace || "/");
    let socket = ns.connected[socketId] // assuming you have  id of the socket
Run Code Online (Sandbox Code Playgroud)