Question on TcpStream and keep connections open


I was trying out the code snippet listed here ( to learn about writing a simple TCP client talking to a ncat instance. In the snippet given, once the client receives data from back ncat, it will close the connection.

Is there a way to keep the connection alive such that data can keep flowing both ways until the user explicitly terminate it?

Sure. Don't let it go out of scope before that.

While I still did not use Rust`s TCP connection, I just wanted to point out that regarding this

TCP connections are slightly more complicated than that. Either side can terminate , and you end up with half-terminated connections. So strictly speaking keeping both ways flowing does not depending only on your side (unless you do control both sides of the connection).

If you want to see what is really happening you can try to capture your flow with Wireshark.

I managed to get an example working but I am not sure if its the right way to do it. What I noticed was that if I used the following;

I cannot write to the ncat terminal as my program is listening for input on its own terminal. So I cloned the TcpStream (stream.try_clone()) and spawn two threads, one for reading using the original TcpStream and one for writing using the cloned TcpStream.

  • Is this a suitable way to do it?

My intention is that both threads will run infinite loops (listening and writing) and the communication will be terminated when I pressed Ctrl+C to close the program.

This topic was automatically closed 90 days after the last reply. We invite you to open a new topic if you have further questions or comments.