I have been sending binary data between applications lots of times over TCP sockets but never before using strings. Bumbed into an issue intending to do so. Here is what I got:
TcpClient tcpClient = new TcpClient("localhost", port);
//Connects fine
NetworkStream ns = tcpClient.GetStream();
StreamWriter sw = new StreamWriter(ns);
//The code moves on but nothing seems to be sent unless I do
//a sw.Close() after this line. That would however close the
//ns and prevent me from reading the response further down
sw.Write("hello");
//I am using a stream reader with ReadToEnd() on the tcpListener
//which never receives the string from this piece of code
//Since the above never actually send I get stuck here
string response = new StreamReader(ns).ReadToEnd();
sw.Close();
tcpClient.Close();
How do I send the string without closing the network stream? ns.Flush() is what I would be looking for really.
You have an sw.Flush()
, that ought to work. A WriteLine()
might have done it too.
But when the other side does a ReadLine() then you have to make sure you end with newline. Try WriteLine() instead of Write().
And be careful about closing a StreamReader/Writer, they also close their underlying streams.
There's a StreamWriter.Flush()
. When you get done with sending you message, just do sw.Flush()
. However, since buffer sizes are fairly large (upto a couple KB), the correct way is to only Flush()
just before you wait for a response. That way several calls to .Write()
can be bundled into a single packet and sent down the wire at the same time.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With