How to leave a socket room with vue-socket and rejoin without duplicate messages? - node.js

When I join the room, and then leave the route and go back, and then use the chat I've built, I get double messages of * amount of messages as many times I left and rejoined.
This problem goes away when I hard refresh.
I've tried everything I could find thus far, and have been unable to get it to work.
I tried on the client side, during beforeRouteLeave, beforeDestroy and window.onbeforeunload
this.$socket.removeListener("insertListener"); --> tried with all
this.$socket = null
this.$socket.connected = false
this.$socket.disconnected = true
this.$socket.removeAllListeners()
this.$socket.disconnect()
During the same events, I also sent a this.$socket.emit("leaveChat", roomId) and then on the server side tried the following inside the io.on("connection") receiver socket.on("leaveChat", function(roomId) {}):
socket.leave(roomId) --> this is what should according to docs work;
socket.disconnect()
socket.off() -- seems to be deprecated
socket.removeAllListeners(roomId)
There were a bunch of other things I tried that I can't remember but will update the post if I do.
Either it somehow disconnects and upon rejoining, previous listeners or something is still remaining, meaning all the messages are received * times rejoin. OR, if I disconnect, I don't seem to be able to reconnect.
On joining, I emit to server the room id and use socket.join(roomId).
All I want to do, is without refresh, when I leave the page, before that happens, the user can leave the room and when they go back, they get to rejoin, with no duplicate messages occurring.
I am currently trying to chew through the source code now.

Full disclosure here, I didn't read the full response posed by roberfoenix, but this is a common issue with socket.io and it comes down to calling the 'on' event multiple times.
When you create an .on event for your socket its a bind, and you can bind multiple times to the same event.
My assumption is, when a users hits a page you run something like
socket.on("joinRoom", data)
This in turn will say join the room, pull your messages from Mongo(or something else) and then emit to the room (side note, using .once on can help so you don't emit to every users when a user joings a room)
Now you leave the room, call socket.emit('leaveRoom',room), cool you left the room, then you go back into the room, guess what you now just binded to the same on event again, so when you emit, it emits two times to that user etc etc.
The way we addressed this is to place all our on-events into a function and call the function once. So, a user joins a page this will run the function like socketInit();
The socketInit function will have something like this
function socketInit(){
if (init === false){
//Cool it has not run, we will bind our on events
socket.on("event")
socket.on("otherEvent")
init = true;
}
}
Basically the init is a global variable, if is false, bind your events, otherwise don't rebind.
This can be improved to use a promis or could be done on connect but if a users reconnects it may run again.

If you're using Vue-Socket and feel like going slightly mad having tried everything, this may be your solution.
Turns out challenging core assumptions and investigating from the ground up pays off. It is possible that you forgot yourself so deeply in Socket.io, that you forgot you were using Vue-Socket.
The solution in my case was using Vue-Socket's built in unsubscribe function.
With Vue-Socket, one of the ways you can initially subscribe to events is as follows:
this.sockets.subscribe('EVENT_NAME', (data) => {
this.msg = data.message;
});
Because you're using Vue Socket, not the regular one, you also need to use Vue Socket's way for unsubscribing right before you leave the room (unless you were looking for a very custom solution). This is why I suspect many of the other things I tried didn't work and did next to nothing!
The way you do that is as follows:
this.sockets.unsubscribe('EVENT_NAME');
Do that for any events causing you trouble in the form of duplicates. The reason you'd be getting duplicates in the first place, especially upon rejoining post leaving a room, is because the previous event listeners were still running, and now the singular user would be playing the role of as if two or more listeners.
An alternative possibility is that you're emitting the message to everyone, including the original sender, when you should most likely be emitting it to everyone else except the sender (check here for socket.io emit cheatsheet).
If the above doesn't solve it for you, then make sure you're actually leaving the room, and doing so server-side. You can accomplish that through emitting a signal to the server right before leaving the route (in case you're using a reactive single page application), receiving it server side, and calling 'socket.leave(yourRoomName)' inside your io.on("connection", function(socket) {}) instance.

Related

socket.io leave current room and join after button is clicked

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
Heading
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:
User clicks button
Client code does socket.emit('next')
Server receives next message
Server calls socket.leave(socket.current_room) to leave the current room
Server does a .emit('next') to everyone still in that room
Server calls socket.join(room) (I have no idea where the room variable comes from)
Clients receive next message and that causes them to socket.disconnect() and thensocket.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.

NodeJS emit to specific room [socket.io]

It seems that I'm not the only one struggling with this problem.
However I am trying to write a simple chat application. When a user joins a room, the roomID is saved in socket.room.id. It is just a number.
When they join / change rooms, I have the following code:
// Notify the rooms
if(previousRoomID) io.to(previousRoomID).emit("activity-notification","<b>"+socket.me.name+"</b> has left the room " + previousRoomID);
io.to(socket.room.id).emit("activity-notification","<b>"+socket.me.name+"</b> has joined the room " + socket.room.id);
Now, Let's say that previousRoomID = 1, and socket.room.id = 30.
It sends the message, but they both seem to go to all users. If I am in roomID 1, and a user leaves the room, I get the following messages:
user has left the room 1
user has joined the room 30
I shouldnt be able to see the second message, because in the code above I am sending it to io.to(socket.room.id).emit(), yet even when I am in room 1 I am getting this message.
Strangely enough also, It seems to be using the broadcast functionality as well, even though I am not calling it; as in - it sends it to all users except the one who fired the event.
What am I doing wrong?
Okay so I have this figured out. The problem was I was calling
socket.join(roomID)
But I wasn't leaving a room first. So it turns out that a socket can join multiple rooms, which would explain why I was seeing both the messages.
if(previousRoomID) socket.leave(previousRoomID);
socket.join(roomID)
if(previousRoomID) io.to(previousRoomID).emit("activity-notification","<b>"+socket.me.name+"</b> has left the room");
io.to(socket.room.id).emit("activity-notification","<b>"+socket.me.name+"</b> has joined the room");
I dont understand the broadcast functionality though, in theory the messages should be going to everyone but for some reason the socket that calls the io.to.emit line doesnt get the activity-notification.

How can I simulate latency in Socket.io?

Currently, I'm testing my Node.js, Socket.io server on localhost and on devices connected to my router.
For testing purposes, I would like to simulate a delay in sending messages, so I know what it'll be like for users around the world.
Is there any effective way of doing this?
If it's the messages you send from the server that you want to delay, you can override the .emit() method on each new connection with one that adds a short delay. Here's one way of doing that on the server:
io.on('connection', function(socket) {
console.log("socket connected: ", socket.id);
// override the .emit() method
const emitFn = socket.emit
socket.emit = (...args) => setTimeout(() => {
emitFn.apply(socket, args)
}, 1000)
// rest of your connection handler here
});
Note, there is one caveat with this. If you pass an object or an array as the data for socket.emit(), you will see that this code does not make a copy of that data so the data will not be actually used until the data is sent (1 second from now). So, if the code doing the sending actually modifies that data before it is sent one second from now, that would likely create a problem. This could be fixed by making a copy of the incoming data, but I did not add that complexity here as it would not always be needed since it depends upon how the caller's code works.
An old but still popular question. :)
You can use either "iptables" or "tc" to simulate delays/dropped-packets. See the man page for "iptables" and look for 'statistic'. I suggest you make sure to specify the port or your ssh session will get affected.
Here are some good examples for "tc":
http://www.linuxfoundation.org/collaborate/workgroups/networking/netem

how to delete a room in socket.io

I want to statically remove all users from a room, effectively deleting that room. The idea is that another room with the same name may be created again in the future, but I want it created empty (without the listeners from the previous room).
I'm not interested in managing the room status myself but rather curious as if I can leverage socket.io internals to do this. Is this possible? (see also this question)
Is that what you want ?
io.sockets.clients(someRoom).forEach(function(s){
s.leave(someRoom);
});
For an up-to-date answer to this question, everyone who wants to remove a room can make use of Namespace.clients(cb). The cb callback will receive an error object as the first argument (null if no error) and a list of socket IDs as the second argument.
It should work fine with socket.io v2.1.0, not sure which version is the earliest compatible one.
io.of('/').in('chat').clients((error, socketIds) => {
if (error) throw error;
socketIds.forEach(socketId => io.sockets.sockets[socketId].leave('chat'));
});
#See https://github.com/socketio/socket.io/issues/3042
#See https://socket.io/docs/server-api/#namespace-clients-callback
Also, it's worth mentioning that...
Upon disconnection, sockets leave all the channels they were part of
automatically, and no special teardown is needed on your part.
https://socket.io/docs/rooms-and-namespaces/ (Disconnection)
if you are using socket io v4 or greater you can use this:
io.in("room1").socketsLeave("room1");
//all the clients in room1 will leave romm1
//hence deleting the room automatically
//as there are no more active users in it

What is the correct way to hang up a video call in vLine?

I am currently using Client.stopMediaSessions(). Is this correct? From what I read in the documentation, and see in the examples, this seems to be the right way to do it.
This should stop both local and remote streams, correct?
What event(s) is/are fired when stopMediaSessions() is called? From my logs, it doesn’t seem that the handler for mediaStream:end is being called. Should it be? Or is enterState:closed the only event fired? Or are both fired?
My question has to do with removing the <video> elements from the DOM – both for the remote and local elements. In your example for MediaStream in the API Reference, the addStream() function handles both mediaStream:start and mediaStream:end events. However, when using this to add both local and remote streams, you can’t count on the mediaElement variable in the mediaStream:end handler because nothing ties that var to the stream, so you don’t know which element to do a removeChild() on.
Anyway, that’s not a big deal. I am just curious what the sequence of events is when a stopMediaSessions() is called; from that I can ensure the right <video> element is being removed.
But in general, I do want to know what the correct way is to hang up/terminate a video call among a set of participants.
Thanks a lot!
client.stopMediaSessions() will stop all vline.MediaSessions for the given vline.Client, so yes, it will "hang up" a call.
To "hang up" an audio/video session with a specific user (vline.Person), you can use Person.stopMedia().
A vline.MediaSession can have local and remote vline.MediaStreams associated with it, so by stopping a vline.MediaSession you will implicitly stop all vline.MediaStreams associated with it.
Since client.stopMediaSessions() is stopping all of the vline.MediaSession's (and therefore vline.MediaStream's), you should get both a mediaStream:end event (from the vline.MediaStream) and a enterState:closed event (from the vline.MediaSession).
For adding and removing <video> elements and keeping track of them, I'd suggest doing something similar to what the vLine shell example does. It uses the unique MediaStream ID to name the div that it puts the <video> element in:
mediaSession.on('mediaSession:addLocalStream mediaSession:addRemoteStream', function(event) {
var stream = event.stream;
// guard against adding a local video stream twice if it is attached to two media sessions
if ($('#' + stream.getId()).length) {
return;
}
$('#video-wrapper').append(elem);
});
// add event handler for remove stream events
mediaSession.on('mediaSession:removeLocalStream mediaSession:removeRemoteStream', function(event) {
$('#' + event.stream.getId()).remove();
});

Resources