我用 C# 编写了一个 Tcp 客户端,用 C++ 编写了一个 Tcp 服务器在 TCP 服务器端,我通过循环接收数据:
unsigned char* buffer = new unsigned char[BUFFERSIZE];
int pLen =0;
int recievedLen = 0;
do{
recievedLen = OnReadData(0, clientSock,buffer,&pLen,1000);
printBytes(buffer,recievedLen);
}while(recievedLen>0);
在 TCP 客户端,我发送一些数据并收到响应:
private void Send(string data)
{
NetworkStream stream = tcpClient.GetStream();
byte[] writeBuffer = Encoding.ASCII.GetBytes(data);
stream.Write(writeBuffer, 0, writeBuffer.Length);
Console.WriteLine("写入数据:" + Encoding.ASCII.GetString(writeBuffer));
}
private void Receive()
{
NetworkStream stream = tcpClient.GetStream();
var readBuffer = new byte[2048];
while (!stream.DataAvailable)
{
Thread.Sleep(1);
}
int writeCount = stream.Read(readBuffer, 0, readBuffer.Length);
String content = Encoding.ASCII.GetString(readBuffer, 0, writeCount);
Console.WriteLine("读取数据:" + content);
}
Q:当我只是在TCP Client 端发送数据而不调用Recieve 数据时,TCP Server 端接收数据的循环可以和谐的完成。但是当在 TCP Client 端调用 Send 函数然后调用 Receive 函数时,TCP Server 端的recv函数会在第二次被阻塞(预期结果是接收 0 字节)。任何人都可以解释一下吗?谢谢