my question is about socket rooms and leave and joining in rooms .my problem is that : i am creating chatroom and i want whenever user (socket) clicks "next person" button (in my case link) i want socket to disconnect (leave) its current room and join another one where another socket is waiting for second socket. like in Omegle
so i tried this code
client-side:
N.addEventListener('click', function(e){
socket.emit('next')
});
socket.on('next',function(){
socket.disconnect()
document.GetElementById('divd').style.display = "inline";
socket.connect()
});
server-side:
socket.on('next', function(){
socket.leave(socket.current_room)
chnm.in(socket.current_room).emit('next');
socket.join(room)
});
but whenever i click "next" it only shows both socket disconnect div like in disconnect event but does not lets socket which triggered that event to join other room rooms in my case is like that
var room = "room" + numb;
socket.current_room = room;
but what i want is to show in room (where socket disconnected) that socket disconnected and socket which triggered that event to be joined in other room . (example: in room 1 socket triggered "next" link he/she disconnects from the room 1 and joins to room 2 and in room 1 appears disconnect div, i think it will appear anyway if i use socket.disconnect() because i already created disconnect event . thanks guys for help <3
There's still not enough code shown or enough of the overall design described that you're trying to achieve, but here's what I can see from what you've shown so far.
Here's your sequence of events:
socket.emit('next')
next
messagesocket.leave(socket.current_room)
to leave the current room.emit('next')
to everyone still in that roomsocket.join(room)
(I have no idea where the room
variable comes from)next
message and that causes them to socket.disconnect() and then
socket.connect()` (no idea why it's doing that).The things that seem odd to me about this sequence of events are:
The socket.disconnect()
followed by the socket.connect()
is completely unnecessary and probably causing problems. First off, these events are asynchronous. If you really wanted to do one followed by the other, you need to wait for the disconnect to finish before trying to do the reconnect. But, mostly, there should be no reason to disconnect and then reconnect. Just update the state of the connection you already have.
I don't follow why when you assign someone to a new room, you then disconnect everyone else who was in that room.
Please don't use the same message name next
to mean one thing when the client receives it and something completely different when the server receives it. This isn't a programming error per se, but it really makes your code hard to understand. Give each its own descriptive name.