TCP套接字无法读取

时间:2018-03-20 11:30:10

标签: c#

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();
}

代码是异步但我认为我做了一些错误,所以让它同步

1 个答案:

答案 0 :(得分:1)

每次执行读取时,您都会覆盖缓冲区的开头,并且只会返回while循环的最后一次迭代中读取的数据。

因此,您需要使用读取的数据量增加i,然后在将数据复制到缓冲区时将其用作偏移量。

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();
}

请注意,如果收到超过10,000个字节,则会抛出异常。

您可能无法读取流中的所有数据,因为stream.DataAvailable只能说明是否可以读取数据,而不是流已完成。