C# TCP套接字不是';t阅读

C# TCP套接字不是';t阅读,c#,C#,代码是异步的,但我认为我做错了什么,所以让它同步。每次读取时,您都会覆盖缓冲区的开头,并且只返回在while循环的最后一次迭代中读取的数据 因此,在将数据复制到缓冲区时,您需要增加读取的数据量i,然后将其用作偏移量 private byte[] ResponseAsync(byte[] buffer, string ip, int port) { byte[] buffer_ = new byte[10000]; // receiving buffer 10KB TcpClien

代码是异步的,但我认为我做错了什么,所以让它同步。每次读取时,您都会覆盖缓冲区的开头,并且只返回在
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());
        i = stream.Read(buffer_, 0, 1024);
    }

    return buffer_.Take(i).ToArray();
}
但请注意,如果接收的字节数超过10000字节,则会引发异常


很可能您不会以
流的形式读取流中的所有数据。DataAvailable
只会说明是否有可读取的数据,而不是流是否已完成。

请注意,TCP不提供消息-它在两个方向上提供无限的字节流。目前,您的代码可以一次读取一个字节(理论上),并不断覆盖缓冲区中的数据,因为您总是提供相同的缓冲区,并告诉系统从一开始就填充它。仍然不起作用我打开wireshark以确保服务器返回某些内容,我是否会因为没有编写异步而丢失流?“我可能缺少流吗…?”--不;服务器的任何响应都会被缓冲。不清楚为什么要写入10kB的垃圾(未初始化的数据)但是到服务器。@RogerLipscombe
buffer
被传入并发送到服务器,而
buffer\uu
由服务器的响应填充。虽然确实应该对问题发表评论,但不是我的答案。
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();
}