I followed a tutorial and was able to copy/build a simple real time web app. I understand everything from the code except for one thing. The 'disconnect' event. I removed most of the code for simplification, but it goes like this:
//server.js
io.on('connection', (socket) => {
//...I removed code from here for simplification
socket.on('disconnect', () => {
socket.broadcast.emit('user-disconnected', users[socket.id]);
delete users[socket.id];
})
})
//client.js
//...a lot of code removed from here for simplification
socket.on('user-disconnected', myname =>
{appendMessage(`${myname} left`)}
)
For my surprise, this code works and when an user closes the window or leaves the page it appends the message the user left, but how does it know the user left? As far as I know, the 'disconnect' word is just a string with no other semantic meaning, right? I mean, it's not like, for example, the addEventListener('click') function which 'click' is a built-in event which means something. From my understanding, the events in socket.io are 'made-up' words by the programmer to help with server/client communication, right? Therefore, I don't understand how leaving the page triggers the 'disconnect' event here. Would someone enlighten me, please?
The disconnect
event is a built-in socket.io event that tells you when a client disconnects.
The socket.io client JavaScript uses the beforeunload
event listener on the window, which executes before the tab closes, then sends a "I'm gonna die" message to the server, then vanishes.
The server can also attempt to ping the client and if nothing returns, oops, disconnected.
On the other hand, the client can manually disconnect from the server with:
socket.disconnect();
This sends a disconnect message to the server then disconnects. You can reconnect with:
socket.connect();