socket.io
socket.io copied to clipboard
Send reason for connection to server
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) => {
// ...
});
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
For future readers:
Please check https://socket.io/docs/v4/connection-state-recovery