How can server detect that client has been disconnected and trigger function in socket.on('disconnect') on serverside. Similar to client, it also has socket.on('disconnect') will trigger on clientside when server closed. I have set the very high pingInterval and very high pingTimeout on server but it seems both server and client can detect the other has been disconnected immediately (by trigger on('disconnect') event).
A regular disconnect is detected when the TCP connection is closed for whatever reason. The server will see a TCP connection get closed when a web page either closes the socket.io connection manually or when the page is navigated away from and the browser closes all open connections from that web page. So, when the connection is operating normally and is then closed by either client or server, the other end will see the closed TCP connection immediately. This has nothing to do with the ping or pong intervals. Those are used for something else (described below).
Since a TCP socket can still be technically connected (not closed yet), but may actually be inoperable and not working any more, ping and pong are used to determine if a connection that still has such an open TCP socket is no longer working. If that is found to be the case (not getting a timely response from the other side from ping/pong), then the socket is closed and the disconnect event is then generated.
About ping/pong packet, is that both sides (server and client) will send a 'ping' to the other and wait for the 'pong' response back or the only serverside send 'ping' to client and client send back 'pong' to server when it receives 'ping' packet.
I cannot find any definitive documentation on this, but it looks like the server code is expecting to receiving ping
messages from the client and it will close the connection if no ping or other data packet is received within a certain timeout period. As soon as the server receives a ping
, it immediately sends a pong
back to the client. So, presumably the client is sending the ping
and looking for a pong
response within a certain amount of time. If it doesn't find the pong
response within a certain time, then it will close the connection on its end (and may attempt a reconnect, depending upon configuration).