Ayy
Ayy

Reputation: 488

TCP socket isn't reading

private byte[] ResponseAsync(byte[] buffer, string ip, int port)
{
    byte[] buffer_ = new byte[10000]; // receiving buffer 10KB
    TcpClient client = new TcpClient(ip, port);
    NetworkStream stream = client.GetStream();
    stream.Write(buffer, 0, buffer.Length);

    //await write;
    int i = 0;

    while (stream.DataAvailable)
    {
        MessageBox.Show(i.ToString());
        i = stream.Read(buffer_, 0, 1024);
    }

    return buffer_.Take(i).ToArray();
}

the code was async but I thought I was doing somethign wrong so made it synchrone

Upvotes: 1

Views: 93

Answers (1)

phuzi
phuzi

Reputation: 13060

You're overwriting the beginning of your buffer each time you do a read and will only return the data read in the last iteration of the while loop.

As such you'll need to increment i with the amount of data read and then use that as the offset when copying data in to your buffer.

private byte[] ResponseAsync(byte[] buffer, string ip, int port)
{
    byte[] buffer_ = new byte[10000]; // receiving buffer 10KB
    TcpClient client = new TcpClient(ip, port);
    NetworkStream stream = client.GetStream();
    stream.Write(buffer, 0, buffer.Length);

    //await write;
    int i = 0;

    while (stream.DataAvailable)
    {
        MessageBox.Show(i.ToString());
        // write data to the appropriate point in buffer_ and update i
        i += stream.Read(buffer_, i, 1024);
    }

    return buffer_.Take(i).ToArray();
}

Be aware though that if you receive more than 10,000 bytes this will throw an exception.

The chances are that you'll not read all the data from the stream as stream.DataAvailable will only say whether there's data available to be read not that the stream has finished.

Upvotes: 1

Related Questions