Empresas
Empleos
  • Sobre nosotros
  • Soluciones
    • Publicación de vacantes
      Publica tu vacante y recibe candidatos calificados en 48h.
    • Evaluación de candidatos
      500+ pruebas técnicas y psicológicas, más anti-fraude.
    • Headhunting
      Búsqueda ejecutiva a la medida de principio a fin.
    • Nómina + EOR
      Dispersión de nómina y EOR en más de 15 países de LATAM.
  • Precios
  • Empleos

0

522
Vistas
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 Respuestas
Responde la pregunta

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 Denunciar
Responde la pregunta
Encuentra empleos remotos

¡Descubre la nueva forma de encontrar empleo!

Top de empleos
Top categorías de empleo
Empresas
Publicar vacante Precios Comercial
Legal
Términos y condiciones Política de privacidad
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Recomiéndame algunas ofertas
Necesito ayuda