Node.js 断开连接期间无法记录套接字 ID

Unable to log socket id during disconnection in Node.js

我正在尝试在用户退出聊天室时记录套接字 ID。 目前记录器说 'transport close has left the chatroom' 而不是记录套接字 ID。

我已经能够让它记录 'transport close' 或 'undefined' 但似乎无法让它在连接关闭前保存 socket.id。我做错了什么?

io.on('connection', function(socket){
    var user_id = socket.id;
    io.emit('broadcast', `--${user_id} has joined the chat room`);
    console.log(`[${user_id}] has joined the chat room`);
socket.on('chat message', function(msg){
    io.emit('chat message', `[${user_id}] ${msg}`);
    console.log(`[${user_id}] ${msg}`);
});
socket.on('disconnect', function(user_id){
    io.emit('broadcast', `${user_id} has left the chat room`);
    console.log(`${user_id} has left the chat room`);
    })
});

使用 socket.id 而不是 user_id。您的回调 function(user_id) 不正确。

socket.on('disconnect', function(){
       io.emit('broadcast', socket.id + ' has left the chat room');
       console.log(socket.id + ' has left the chat room');
})