TCPClient 缓冲区大小异常

TCPClient Buffer size exception

我正在使用简单的 TCP 客户端应用程序向服务器发送请求。 这是将客户端消息发送到服务器的客户端代码。 服务器发送响应,但有时响应为空字符串。

发生断点时我发现了一个断点,当我将鼠标放在 client.ReceiveBufferSize 上时它显示异常 ObjectDisposedException

代码如下:

private string SendClientMsg(string textToSend, string handID)
{ 
    TcpClient client = new TcpClient(serverIP, port);
    NetworkStream nwStream = client.GetStream();
    //---create a TCPClient object at the IP and port no.---
    byte[] bytesToSend = ASCIIEncoding.ASCII.GetBytes(textToSend);

    //---send the text---
    nwStream.Write(bytesToSend, 0, bytesToSend.Length);

    //---read back the text---
    byte[] bytesToRead = new byte[client.ReceiveBufferSize];
    int bytesRead = nwStream.Read(bytesToRead, 0, client.ReceiveBufferSize);
    string response = Encoding.ASCII.GetString(bytesToRead, 0, bytesRead);
    client.Close();
    return response;
    }
 }

此方法属于class。 多个线程正在使用此方法向服务器发送请求。 会不会是一个线程打开连接开始发送 但同时另一个线程使用 client.Close()

关闭连接

我不确定是否所有线程都共享同一个 TcpClient 对象。 (它是一个单例对象,所以它被所有线程共享吗?)。 如果是这样,我将不得不锁定以确保多个线程不会同时访问此方法。

每次调用此方法都会创建一个 TcpClient 的新实例:

TcpClient client = new TcpClient(serverIP, port);

只有调用线程可以访问此实例,所以这不是问题。

问题是您假设您将收到整个
单次阅读回复:

int bytesRead = nwStream.Read(bytesToRead, 0, client.ReceiveBufferSize);

来自MSDN

The total number of bytes read into the buffer. This can be less than the number of bytes requested if that many bytes are not currently available, or zero (0) if the end of the stream has been reached.

服务器响应需要时间,响应需要时间
通过网络发送。当你调用 Read 整个响应 可能可用也可能不可用,因此您需要循环读取直到 已到达流的末尾。

var responseBuffer = new byte[client.ReceiveBufferSize];
var bytesRead = 0;
int read;
do
{
   read = nwStream.Read(responseBuffer, 0, client.ReceiveBufferSize);
} while (read > 0)

这是假设服务器在处理请求后正确关闭连接。
如果连接保持打开状态,您将不得不恢复到不同的方法
以确定您已收到对请求的完整响应。