You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

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

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.09.27 17:45:00