Slashy
Slashy

Reputation: 1881

C# Networkstream reads nothing

Just trying to use Networkstream, and this is a simple code i wrote:

Client side:

       TcpClient c = new TcpClient();
        c.Connect("10.0.0.4", 10);
       NetworkStream ns = c.GetStream();
        byte[] buffer = System.Text.Encoding.UTF8.GetBytes("first");
        byte[] buffer2 = System.Text.Encoding.UTF8.GetBytes("second");
        MemoryStream stream = new MemoryStream();
       stream.Write(buffer, 0, buffer.Length);
        stream.Write(buffer2, 0, buffer2.Length);
        stream.CopyTo(ns);

This is the server side:

        TcpListener tl = new TcpListener(IPAddress.Any, 10);
        tl.Start();
        TcpClient c = tl.AcceptTcpClient();
        NetworkStream   ns = new NetworkStream(c.Client);
        byte[] buff = new byte[5];
        ns.Read(buff,0,buff.Length);
        string result = System.Text.Encoding.UTF8.GetString(buff);
        MessageBox.Show(result);

only when i close the entire application the MessageBox line is executed , and im always getting a blank messagebox! which mean result doesnt contain nothing... Any help?

Upvotes: 2

Views: 455

Answers (1)

usr
usr

Reputation: 171178

On the client stream is positioned at the very end of the stream. Therefore, CopyTo has nothing left to copy.

Use stream.Position = 0; before copying.

Also, you don't seem to be aware of the fact that socket reads (in fact any stream read) can return less bytes than were requested (at least one). Your reading code must account for that. TCP does not preserve message boundaries.

Upvotes: 2

Related Questions