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

Node.js使用ws库时,如何获取断开连接的客户端ID信息

解决ws库中客户端断开连接时识别客户端的问题

错误原因分析

你代码里的close事件写法存在两个问题:

  1. ws.on('close', ..., client)里的第三个参数client未定义,直接导致报错;
  2. ws库的close事件回调参数并非客户端实例,而是连接断开的状态码(code)和原因(reason)。

解决方案:给每个客户端连接分配唯一标识

要识别断开的客户端,你可以在建立连接时给每个ws实例添加唯一ID,之后在close事件中直接通过这个ID区分客户端。

实现方式1:自增ID(无需额外依赖)

var { WebSocketServer, WebSocket } = require('ws')
const ws_server = new WebSocketServer({ port: 8080 });

// 用自增计数器生成客户端ID
let clientIdCounter = 1;

ws_server.on('connection', (ws) => {
    // 给当前客户端连接分配唯一ID
    ws.id = clientIdCounter++;
    console.log(`Client ${ws.id} has connected!`);

    ws.on("message", function(msg,isBinary) { 
        console.log(`Client ${ws.id} sent:`, msg.toString()); 
    });

    // 修正close事件的写法
    ws.on('close', (code, reason) => {
        console.log(`Client ${ws.id} has disconnected! Code: ${code}, Reason: ${reason.toString()}`);
    });
});

实现方式2:使用UUID(适合分布式场景)

如果需要更具唯一性的ID,可以借助uuid库:

  1. 先安装依赖:npm install uuid
  2. 代码实现:
var { WebSocketServer, WebSocket } = require('ws')
const { v4: uuidv4 } = require('uuid');
const ws_server = new WebSocketServer({ port: 8080 });

ws_server.on('connection', (ws) => {
    // 用UUID生成唯一ID
    ws.id = uuidv4();
    console.log(`Client ${ws.id} has connected!`);

    ws.on("message", function(msg,isBinary) { 
        console.log(`Client ${ws.id} sent:`, msg.toString()); 
    });

    ws.on('close', (code, reason) => {
        console.log(`Client ${ws.id} has disconnected! Code: ${code}, Reason: ${reason.toString()}`);
    });
});

额外说明

  • 每个ws实例就是对应的客户端连接,你可以给它挂载任何需要的客户端信息(比如用户ID、来源IP等),例如ws.userId = 'user_123',后续在事件回调中直接访问即可;
  • close事件的reason是Buffer类型,需要用toString()转为可读字符串。

内容的提问来源于stack exchange,提问作者user824624

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.09 14:10:41