So I'm pretty new to it, so I apologize if I this is an entirely wrong approach of doing this, but I am currently programming a little chat application using node.js with express and socket.io. I managed to get a login message logged to the console but I am really struggling with the logout one. When a user opens up the page I take the roomname aswell as the username out of a cookie and send it to the server like shown here:
var socket = io();
var roomname = readCookie('Roomname');
var nickname = readCookie('Nickname');
var data = {'type': 'user', 'channel': roomname, 'user': nickname, 'data': "joined"};
socket.emit('chat', data);
After that I filter the message on the server side and send the answer to all clients like this:
case 'user':
io.emit('chat/' + msg.channel, {type: 'user', user: msg.user, data: msg.data});
break;
I always send the string "chat" followed by the roomname as a channel name so only the users that are in the right rooms can see the message. After that I sort out what kind of message was received by the client side:
case 'user':
console.log(msg.user + " just " + msg.data + " the room!");
break;
Now the only thing I need to do is somehow getting the room- and username to the server side once the user closes the page so I can send the message but with "left". (like this)
var data = {'type': 'user', 'channel': roomname, 'user': nickname, 'data': "left"};
socket.emit('chat', data);
My approach was finding an event that fires the code at the right time and I have been looking through stack overflow for a good hour now and I just couldn't find anything that did the job. I've tryed out all the variations of window.onbeforeunload
I could find and none of them seemed to work. I could log some stuff to the console with some of them but I was never able to emit a message to the server side. I am aware that this may not be possible in the way I would like it to, but I really ran out of ideas what to try next. Can someone help me out?
You can add information about the client's username to the socket object, when the client connects for the first time. Then you will be able to use socket.username when client disconnects.
Client:
var socket = io();
var roomname = readCookie('Roomname');
var nickname = readCookie('Nickname');
socket.on('connect', () => {
socket.emit("hello", {nick:nickname, room:roomname});
});
Server:
socket.on("hello", (data) => {
socket.username = data.nick;
socket.join(data.room);
socket.room = data.room;
});
socket.on("disconnect", () => {
var data = {'type':'user', 'channel':socket.room, 'user':socket.username, 'data':'left'};
socket.broadcast.to(socket.room).emit('chat', data};
socket.leave(socket.room);
});