socket.id of disconnecting client?

2020-07-02 07:57发布

Is it possible to get the socket.id of the client that has disconnected? The following code gives me undefined for socket.id

Node.js Code

io.sockets.on('connection', function() {
    socket.on('disconnect', function(socket) {
        console.log(socket.id);
    });
});

1条回答
冷血范
2楼-- · 2020-07-02 08:32

The callback function that io.sockets.on takes as its second argument is supposed to take one argument: the socket. Yours doesn't, so the socket on the second line's socket.on is undefined.

And the callback for socket.on isn't given any arguments, so the socket in that function is also undefined.

The code should work if you move the socket parameter from the second function declaration to the first:

io.sockets.on('connection', function (socket) {
    socket.on('disconnect', function () {
        console.log(socket.id);
    });
});
查看更多
登录 后发表回答