Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

emit data on disconnect event from client to server on node

I couldnt send the data from the client to server on disconnect event

//clients side

var gname = "asd";
    socket.emit('disconnect',gname);

//server side

    socket.on('disconnect', function (data) {
console.log(data);

        var i = connect_clients.indexOf(data);
        if(i != -1) {
            connect_clients.splice(i, 1);
        }
}
like image 237
ujwal dhakal Avatar asked Nov 21 '15 15:11

ujwal dhakal


1 Answers

You won't be able to, because the socket was disconnected from server. The event on server fires when the server detects disconnect (not magically by a fraction before that) and the "bridge" between client and server is already closed/interrupted/whatever - no connectivity means no data interchange.

You have two options on how to do something with disconnected client:

  1. use database or local variables to store some user information by 'socket.id' (for example track down online users). When you get disconnect event on server you can see socket's id what get disconnected. Use this id to do needed stuff like decrease online users count and broadcast this to others.

  2. (rather bad solution) wait for reconnect event on client and send the data from there when the connection will be reestablished. Of course if the server will remains down the data probably will be lost.

If you need to perform some simple server side stuff, solution 1 may work just fine, but if you have something complex, like unsaved form data, you will have to come up with some sort of saving the data in localStorage, for example, and sync it back upon reconnect.

like image 200
kaytrance Avatar answered Oct 01 '22 00:10

kaytrance