How to get the socket id of a disconnected client on the disconnect event in socket.io
Asked Answered
E

1

5

I have started working on a web application for othello.... in it I used node.js and socket.io for handling the server side code. It runs a server.js file in the cloud.

This file handles some of the main client events, one of them is the disconnect event.

Here's the code for disconnect event:

io.sockets.on('connection', function(socket) {
    log('Client connection by '+socket.id);
    function log(){
        var array = ['*** Server log Message'];
        for(var i=0; i< arguments.length; i++) {
            array.push(arguments[i]);
            console.log(arguments[i]);
        }
        socket.emit('log', array);
        socket.broadcast.emit('log', array);
    }
    /* disconnect command */
    socket.on('disconnect', function(socket) {
    log(socket);
    log('Client disconnected '+ JSON.stringify(players[socket.id]));
    if('undefined' !== typeof players[socket.id] && players[socket.id]) {
        var username = players[socket.id].username;
        var room = players[socket.id].room;
        var payload = {
            username: username,
            socket_id: socket.id
        };
        delete players[socket.id];
        io.in(room).emit('player_disconnected', payload);
    }
    });
});

This disconnect command should notify all the other cleints about the disconnected player and delete the data about it.

Here's the code for holding the temporary data of the active players:

/* join_room command */
socket.on('join_room', function(payload) {
    log('\'join_room\' command '+ JSON.stringify(payload));
    if(('undefined' === typeof payload) || !payload) {
        var error_message = 'join_room had no payload, command aborted';
        log(error_message);
        socket.emit('join_room_response', {
            result: 'fail',
            message: error_message
        });
        return;
    }
    var room = payload.room;
    if(('undefined' === typeof room) || !room) {
        var error_message = 'join_room didn\'t specify a room, command aborted';
        log(error_message);
        socket.emit('join_room_response', {
            result: 'fail',
            message: error_message
        });
        return;
    }
    var username = payload.username;
    if(('undefined' === typeof username) || !username) {
        var error_message = 'join_room didn\'t specify a username, command aborted';
        log(error_message);
        socket.emit('join_room_response', {
            result: 'fail',
            message: error_message
        });
        return;
    }

    /* store information about new player */
    players[socket.id] = {};
    players[socket.id].username = username;
    players[socket.id].room = room;
    log(players);

    socket.join(room);

    var roomObject = io.sockets.adapter.rooms[room];

    /* notify others about new player */


    var sumCleints = roomObject.length;
    var data = {
        result: 'success',
        room: room,
        username: username,
        socket_id: socket.id,
        membership: sumCleints
    };
    io.in(room).emit('join_room_response', data);

    for(var socket_in_room in roomObject.sockets) {
        var data = {
            result: 'success',
            room: room,
            username: players[socket_in_room].username,
            socket_id: socket_in_room,
            membership: sumCleints
        };
        socket.emit('join_room_response', data);
    }
    log('join_room success');

    log('Room: '+ room + ' was just joined by '+ username)
});

But the issue is it doesn't. When I logged the socket.id, it returns undefined, I don't know why ... when I log the socket itself, it says: transport closed.

My question is how to get the socket id of a player who just disconnected.

Here's the client side code for handling the player_disconnected event:

/* when someone leaves a room */
socket.on('player_disconnected', function(payload) {
    if (payload.result == 'fail') {
        alert(payload.message);
        return;
    }

    if(payload.socket_id == socket_id) {
        return;
    }

    /* Delete all rows for new players that leave */
    var dom_elements = $('.socket_'+payload.socket_id);

    if(dom_elements.length != 0) {
        dom_elements.slideUp(1000);
    }

    var newHTML = '<p>'+payload.username+' has left the lobby</p>';
    var newNode = $(newHTML);
    newNode.hide();
    $('#messages').append(newNode);
    newNode.slideDown(1000);
});

If someone could figure out the problem than please tell me, and please tell me how the disconnect event, and the other events actually work and what are the parameters for them, because I couldn't find any useful information in the docs... Thanks in advance.

Erving answered 14/3, 2019 at 5:31 Comment(0)
M
6

On disconnect, you are overriding the socket variable with a different callback parameter. Try this:

/* disconnect command */
socket.on('disconnect', function() {
  console.log(socket.id);
});
Meyeroff answered 14/3, 2019 at 6:58 Comment(3)
yes! you're right, there was this small bug which I was unable to find at first, next time I will take care before asking silly questions ... thanks a lot.Erving
Can you please tell me what are the parameters for the disconnect event? Like if I write the following code :- /* disconnect command */ socket.on('disconnect', function(payload) { console.log(payload); });Erving
There is no predefined parameter as such, but you can pass custom parameters while calling socket.disconnectMeyeroff

© 2022 - 2024 — McMap. All rights reserved.