Does it exist an event to be notified when new data on TcpStream to read ? I don’t want to wait indefinitely since I will not be able to stop my thread at the end.
Or I could ask my question differently : How to close a TcpStream cleanly when a client wants to disconnect from the server ?
You can take a look into Tokio which precisely does that, to fire event, in this case Futures, whenever a new connection is received. This doesn’t have the cost of wait operation, since internally poll is used.
You can also find the examples here.
Besides tokio, there’s the lower level
mio crate (that tokio is based on).
Barring those, you can use a thread-per-connection model where you have blocking IO but it would block a dedicated thread (note this might not scale to lots of clients). If the remote disconnects, the blocked read/write calls would return. For example, a read would return a Ok result with 0 bytes read if the remote shuts down gracefully or it would return an Err if it’s not graceful (eg a reset). You can still get hung calls if the network disappears from you (ie packets lost) and then you can play around with tcp keepalive probes or put in an application level heartbeat/liveness protocol. But that’s now tangential to your question .