首页 > 解决方案 > 通过io.sockets.sockets解析时如何获取socket id

问题描述

我在 Node.js 服务器上使用 Socket.io。

for (connectedSocket of io.sockets.sockets) {
    console.log(`TEST: id = ${connectedSocket.id}`) //Why is this 'undefined'? All I want is the unique identifier of each socket in the server.
}

不知道如何解决这个问题,但它必须非常简单。抱歉,代码格式失败:o

标签: javascriptnode.jssocketssocket.io

解决方案


从 socket.io v3 开始,io.sockets现在是一个Map对象,如下所示。您可以直接使用以下方法对其进行迭代:

for (let [id, socket] of io.sockets.entries()) {
    // can use socket here
}

您可以使用更新的界面:

let socketsArray = await io.fetchSockets();

为您提供一系列连接的套接字。

请注意,您也可以使用房间和命名空间,如此fetchSockets()所示。


推荐阅读