通过 io.sockets.sockets 解析时如何获取套接字 ID

How to get the socket id when parsing through io.sockets.sockets

我在 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

从 socket.io v3 开始,io.sockets 现在是一个 Map 对象,如图 here 所示。您可以直接迭代它:

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

您可以使用更新的界面:

let socketsArray = await io.fetchSockets();

为您提供一组已连接的套接字。

请注意,您还可以将 fetchSockets() 与房间和名称空间一起使用,如 here 所示。