Can you explain why socket.io disconnect doesn't work?

Hi everyone!

I’m using socket.io with Ionic 3.x

My app has two kinds of status. Let’s call the first one “checked in” and the second one “checked out.”

Upon check in I call

this.socket.connect();
this.socket.emit(SERVER_SOCKET_JOIN_ROOM, SERVERSOCKET_TYPE);

This succesfully joins the user and I get all the realtimedata that I need! :slight_smile: Meaning checked in users get certain data over the socket.

Here comes the bad part (you can hopefully advice me on what I did wrong):

When the user checks out or gets checked out, I call

this.socket.disconnect()

According to the socket.io docs the disconnect function automatically leaves all rooms.
I even checked on the server side, if the disconnect was successful:

socket.on('disconnect', function(){
  console.log('Disconnection happened.');
});

It is succesful.
But, when I rejoin the server, all the data passed to the checked in users using the socket now appears twice!

If I repeat the process (check out, followed by a checkin) the user get the data three times!

I checked on the server side: The data only gets put out once (I console logged everytime something gets logged out by the server).

I don’t know what to do, any advice would be much appreciated!

I also experienced this strange behaviour in one of my apps. My current solution is to remove all event listeners which I’ve previously created just before calling disconnect() like this:

this.socket.removeAllListeners('youraction');

The problem otherwise is that these event listeners keep existing although you are logged out from socket!

1 Like

Thank you for your answer saimon! I learned how to use sockets from your video :slight_smile:

So in my example I would have to call:

this.socket.removeAllListeners(SERVER_SOCKET_JOIN_ROOM);

As SERVER_SOCKET_JOIN_ROOM is the event I emit to join the room?

The code on the node app is:

socket.on('join-room', (room) => {
    console.log("Room " + room + " joined");
    socket.join(room);
  });

Yeah I think that should fix the problem! Glad you started out with my video :slight_smile:

1 Like