Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Socket.io send disconnect event with parameter

I want to send disconnect event manually with custom parameter to socket.io server. I use this function but won't work:

//client

var userId = 23;
socket.disconnect(user);

//Server

socket.on('disconnect', function (data) {
        console.log('DISCONNECT: '+  data)
    })

Now how can I send a additional data to server when disconnect event sent?

like image 922
Ehsan Ali Avatar asked Nov 26 '16 08:11

Ehsan Ali


People also ask

Does Socket.IO disconnect after some time?

Yep, I've had same issue actually. But I managed to solve it differently. There was no issue on code side, it was sever configuration issue where it was hosted.

Does Socket.IO reconnect automatically?

In the first case, the Socket will automatically try to reconnect, after a given delay.

Does Socket.IO reconnect after disconnect?

Socket disconnects automatically, reconnects, and disconnects again and form a loop. #918.

How do I stop a Socket.IO server?

close([callback])​ Closes the socket.io server. The callback argument is optional and will be called when all connections are closed.


2 Answers

Socket IO's disconnect event is fired internally but you can emit a custom event when it is called.

You need to first listen for the disconnect event. Once this event has been called, you should then emit your own custom event say we call it myCustomEvent Once this event has been called, your client should then be listening out for your myCustomEvent and on hearing it, should then output the data you passed it. For example:

io.sockets.on('connection', function (socket) {
  const _id = socket.id
  console.log('Socket Connected: ' + _id)
  // Here we emit our custom event
  socket.on('disconnect', () => {
    io.emit('myCustomEvent', {customEvent: 'Custom Message'})
    console.log('Socket disconnected: ' + _id)
  })
})

Your client would then listen for myCustomEvent like so

socket.on('myCustomEvent', (data) => {
    console.log(data)
})

I hope this helps :)

like image 53
Jackthomson Avatar answered Sep 28 '22 03:09

Jackthomson


We can manage a global array at server side.

var sockets = [];
io.on('connection', function (socket) {
    const id = socket.id ;

    socket.on('user-join', function(data) {
         sockets[id] = res.id;
    });

    socket.on('disconnect', function(data) { 
        io.emit('user-unjoin', {user_id: sockets[id],status:'offline'}); 
    });
});

On clients side,

socket.on('user-unjoin', function (data) {
    // update status of data.user_id according to your need.
});

This answer is inspired from Jackthomson's answer.

like image 38
Satyandra Shakya Avatar answered Sep 28 '22 01:09

Satyandra Shakya