Skip to content Skip to sidebar Skip to footer

Socket.io Won't Emit Messages To Rooms On Discconect

Basically I'm trying to create a quick chat room using Node.JS and angular. I've Used other socket events and they worked I don't quite get why they don't want to work now. The rea

Solution 1:

It may fix your issue but you should be using socket.broadcast.to('roomname') unless you want to send the message to all sockets in the room (including the one that sent the message). So your code would look something like

socket.on('chat:userLogin', function(user) {
   socket.join('online-users');
   chatRoom[user.id] = user
   console.log('User Has logged in, chat room contains: ', chatRoom);
   // emit to everyone else except the sender
   socket.broadcast.to('online-users').emit('chat:usersOnline', chatRoom);
})

socket.on('chat:userLogout', function(userId) {
   console.log('User Id ' + userId + 'is logging out');
   delete chatRoom[userId]
   socket.leave('online-users');
   // leaving the chat room here means we can emit to all people in the room
   io.sockets.in('online-users').emit('chat:userLeave', chatRoom);
   console.log('User Has logged out, chat room contains: ', chatRoom);

})

socket.on('disconnect', function() {
   var userRoom = rooms[socket.roomId]

   if (chatRoom[socket.userId])
      delete chatRoom[socket.userId]

   socket.leave('online-users');
   io.sockets.in('online-users').emit('chat:userLeave', socket.userId);

   console.log('Emitting that users have left to: ', io.sockets.in('online-users'));
}

Check out this question for more info.

Post a Comment for "Socket.io Won't Emit Messages To Rooms On Discconect"