Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

read/write string over tcp network stream

Tags:

c#

.net

c#-4.0

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.

like image 967
BlueVoodoo Avatar asked Feb 02 '11 14:02

BlueVoodoo


2 Answers

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.

like image 138
Henk Holterman Avatar answered Oct 16 '22 02:10

Henk Holterman


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.

like image 1
Timothy Baldridge Avatar answered Oct 16 '22 04:10

Timothy Baldridge