0

Everytime a mobile user that is connected to my node.js, socket.io server leaves their browser (maybe checks instagram or something) the socket disconnects due to "transport close".

When they return I want them to reconnect using their old socket so they can receive buffered packets and have access to their old data stored in said socket.

What actually happens is that they reconnect and a new socket is created when the "connection" event is emitted in the server. The old socket is deleted too, unless I store it somewhere.

Are there any simple ways (config or something) to just reuse an old socket when a reconnection happens?

This post helped me a bit: reuse socket id on reconnect, socket.io, node.js. However it doesn't show me how to reuse the actual old socket.

  • an ephemeral socket id !== user id, rather than rely on the socket id being the same you should assign a token or even a simple username or auth to associate messages to a user, personally I send up the same JWT I use for site auth, it has the user id, which then on connect you pull out stuff from db, like name and messages etc – Lawrence Cherone Aug 29 '22 at 13:00

1 Answers1

0

Unfortunately after such event "transport close", by design the socket is destroyed. So at this point you should look to other alternatives. My suggestion is to introduce a new data structure which will store the messages in a list. My proposal involves:

  1. A map where the key is the user id and value is a list which contains all user messages.
  2. You can store an offset to the structure which holds the list which marks the messages sent before the connection problem
  3. On reconnect you lookup the map with the userid and retrieve the user messages
Eduard Hasanaj
  • 865
  • 4
  • 10
  • OK, thank you for the quick response! I though it would be possible to only rely on the things provided by socket io rather than creating my own framework building upon it. That is the reason why I switched from the more primitive "ws" framework. – Charles Maddock Aug 29 '22 at 13:19