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

时间:2018-10-17 12:33:36

标签: node.js sockets server transport

我试图在用户注销聊天室时记录套接字ID。 目前,记录器在说“传输关闭已离开聊天室”,而不是记录套接字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`);
    })
});

1 个答案:

答案 0 :(得分:2)

Use socket.id instead of user_id. Your callback function(user_id) is incorrect.

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