Socket.io: Why socket.io doesn't work after internet reconnection?

Created on 1 Jul 2019  路  5Comments  路  Source: socketio/socket.io

I have a simple chat app, using react-native, nodejs, and socket.io, they all works very well.

But there is some cases which doesn't work as expected.

1. When the application is open.

  • Internet gets disconnect and reconnect again.
  • Internet gets change, from mobile data to wifi or vice versa.
  • Phone goes to sleep and wakes up.

2. When the application is close.

  • We open the application without internet connection, and we connect to the internet while the application is open.

My Expectation:
I want for above cases, it should work as well.

Server:

const onlineusers = {};
io.on('connection', function(socket) {
    socket.on('online', user => {
     onlineusers[user] = cs.id;
     io.emit('online', onlineusers);
    });
    socket.on('message', data => {
      socket.broadcast.to(data.userid).emit('message', data);
    });
});

Client:

this.socket = io('domainname.com:5412', { transports: ['websocket'] });
if(this.socket.connected) {

    this.socket.emit("online", this.myuserid);

    this.socket.on('online', users => {
      console.log('online users', users);
    });

    this.socket.on('connect', ()=> {
      this.socket.emit("online", this.myuserid);
    });

    this.socket.on('message', message => {
      console.log(message);
    });

    this.socket.on('disconnect', reason => {
      if(reason==='io server disconnect') this.socket.connect();
    });
}

sendMessage = message => {
  this.socket.emit('message', message);
}

All 5 comments

it should auto reconnect.. you dont need this

 if(reason==='io server disconnect') this.socket.connect();

and please remove this if(this.socket.connected) {

let the socket io do its job..

and please remove this if(this.socket.connected) {

It鈥檚 needed before calling socket.emit(...), though not for adding the event handlers. All the examples on the socket.io website do it this way, and I鈥檝e experienced myself that if you don鈥檛 do it, socket.io will open multiple concurrent http connections when not connected, sending the same message multiple times when finally connecting.

its redundant connect wont fire if its not connected #if(this.socket.connected)

The connect event won't fire, correct, but it's not redundant as everything sent via socket.emit(...) might get sent multiple times, as I described above. I observed this in practice.

your doing something wrong.. or your using outdated ones .. yes socket io will fire multi times because its auto retrying ... but it wont send multi times if you have slow net or suddenly gets disconnected.. socket io handles it very well. its an event.. an event should be called = * emit ..

Was this page helpful?
0 / 5 - 0 ratings