Business
Jobs
  • About Us
  • Solutions
    • Job Postings
      Post your job and receive qualified candidates in 48h.
    • Candidate Assessments
      500+ technical and psychological tests, plus anti-fraud.
    • Headhunting
      Tailor-made executive search from start to finish.
    • Payroll + EOR
      Payroll dispersal and EOR across 15+ LATAM countries.
  • Pricing
  • Jobs

0

521
Views
How does the disconnect event works in socket.io?

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?

about 4 years ago · Juan Pablo Isaza
1 answers
Answer question

0

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();
about 4 years ago · Juan Pablo Isaza Report
Answer question
Find remote jobs

Discover the new way to find a job!

Top jobs
Top job categories
Business
Post vacancy Pricing Sales
Legal
Terms and conditions Privacy policy
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Show me some job opportunities
There's an error!