Search code examples
javascriptnode.jssocket.ioclient-serverreal-time

I can not connect to Socket.io room after disconnect


On the first connection users successfully join rooms. However, after disconnection, room re-join fails. This code returns room as undefined when I try to connect after room disconnect.

Any good ideas how to deal with Socket.io re-connections?

Server:

io.on('connection', function onConnection(socket){
   socket.on('adduser', function(data){
      socket.room=data.room ; 
      socket.join(socket.room)
          })

   })

socket.on('drawing', function(points) {
       console.log("on room"+ socket.room)//logs undefined on reconnect 
        io.to(socket.room).emit('drawing', points);

console.log("broadcasting")
 });

on disconnect:

  socket.on('disconnect', function(){
       console.log(socket.room)

       socket.leave(socket.room);

})

Client:

var socket = io.connect(':3000');

socket.on('connect', function(){
        console.log("emit socket")
    socket.emit('adduser', data);
  })

Solution

  • so it seems that connection is not closed when a user disconnects because of Socket.io default behavior

    this can be fixed by forcing new connection on loading so on client side replace:

    var socket=io.connect(':3000')
    

    with

    var socket=io.connect(':3000', {'force new connection': false})