Node.js中使用Socket.io遍历io.sockets.sockets时如何获取socket id
Socket.io遍历连接获取socket id为undefined的解决方案
问题原因
io.sockets.sockets在Socket.io 3.x及以上版本为Map结构,使用for...of直接遍历Map时,每次迭代返回的是[socket唯一id, socket实例]格式的数组,直接对数组取.id属性不存在,因此输出undefined。
修复方案
方案1:遍历Map时直接解构取值
for (const [socketId, connectedSocket] of io.sockets.sockets) { // socketId即为连接的唯一标识,和connectedSocket.id完全等价 console.log(`TEST: id = ${socketId}`) }
方案2:提取所有socket实例后遍历
// 先取出Map中所有的socket实例转为数组 const allConnectedSockets = Array.from(io.sockets.sockets.values()) for (const connectedSocket of allConnectedSockets) { console.log(`TEST: id = ${connectedSocket.id}`) }
方案3(Socket.io v4+推荐):使用官方API获取连接
该方法适配多节点部署、自定义命名空间等复杂场景,兼容性更强:
// 注意该方法是异步方法,需要在async函数内调用 const allConnectedSockets = await io.fetchSockets() for (const connectedSocket of allConnectedSockets) { console.log(`TEST: id = ${connectedSocket.id}`) }
内容的提问来源于stack exchange,提问作者nickcoding2
相关产品推荐
相关产品推荐

