socket.io icon indicating copy to clipboard operation
socket.io copied to clipboard

Send reason for connection to server

Open gillerby opened this issue 4 years ago • 1 comments

Is your feature request related to a problem? Please describe. When a socket connects to the server, e.g., for a chat application, I do not know out of the box if this is a reconnect or a new connection. If it is a reconnect, I'd like to add the user to his previous room, while a new user would get a new one, etc etc.

Describe the solution you'd like Ideally somehow the reason for connection would be available in the 'connection' block. e.g., by quering socket.connReason

io.on("connection", (socket) => {
  // ...
});

gillerby avatar Jul 27 '21 13:07 gillerby

Hey! You can listen to the reconnect event on the client and emit a custom event to the server with client-identifying / unique info, e.g.,

Client

socket.on('reconnect', function () {
   socket.emit('customReconnectEvent', { data: someUniqueData })
})

after which you can handle the event by creating a map of the socket.id and data (example), discarding the previous socket.id used before the reconnection.

Server

const userMap = {}

io.on('connection', function (socket) { 
   const socketId = socket.id
   userMap[socketId] = 'new connection'
   
   socket.on('customReconnectEvent', function (message) {
      userMap[socketId] = message.data
      // do something with user
   })
})

It's a little bit of a wonky solution, but it might work

nandanv2702 avatar Oct 27 '21 00:10 nandanv2702

For future readers:

Please check https://socket.io/docs/v4/connection-state-recovery

darrachequesne avatar Feb 17 '23 23:02 darrachequesne