Empresas
Empregos
  • Sobre nós
  • Soluções
    • Publicação de vagas
      Publique sua vaga e receba candidatos qualificados em 48h.
    • Avaliações de candidatos
      Mais de 500 testes técnicos e psicológicos, mais anti-fraude.
    • Headhunting
      Busca executiva personalizada do início ao fim.
    • Folha de Pagamento + EOR
      Dispersão de folha e EOR em mais de 15 países da LATAM.
  • Preços
  • Empregos

0

529
Visualizações
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 Respostas
Responde à pergunta

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 Relatório
Responde à pergunta
Encontrar trabalhos remotos

Descubra a nova forma de encontrar um emprego!

melhores empregos
Principais categorias de trabalho
Empresas
Postar vaga Preços Comercial
Jurídico
Termos e Condições Política de privacidade
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Recomende algumas ofertas para mim
Preciso de ajuda