With tokio TcpListener, while awaiting a read operation, what is the proper way to detect network issues (say, cable unplugged, network card unplugged etc)?
I was surprised to find out read() doesn't return an error, but instead continues awaiting after I pull the cable.
I could only find this thread, but it deals with issues on the client side. https://users.rust-lang.org/t/tokio-detect-connection-loss/116217/3
There is no difference between client and server, here. Once established, a TCP connection is completely symmetric. The answer is the same in both cases — the only way to know the connection is working is to try to communicate through it.
For a server, this often means that the server has a timeout for inactive connections, and the client has the obligation to either get its business done quickly, or send some kind of ping message.
Strange though the following example doesn't detect the disconnected network cable (and it does both read and write). So the only reliable way shall be sending a heartbeat and receiving a reply.
For some reason the keepalive doesn't work too (the same idea of having a heartbeat, but invisible to the application), perhaps because it's Friday evening and I am missing something.
Have you tried plugging the network cable back in? The reason it works this way was because they wanted a tcp stream to be able to survive temporarily losing the connection.
When you try to send data, and the data can't actually be sent down the cable (or more precisely, when the other end doesn’t respond with an ACK), a timer starts (inside the network stack, not your process). When that timer runs out, the socket will be closed with an error, if the cable isn’t plugged back in before then.