我用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);
}
问: 当我只是发送数据而不在TCP客户端调用接收数据时,在TCP服务器端接收数据的循环可以完成和谐。但是当调用Send函数然后在TCP客户端调用Receive Function时,TCP Server端的 recv 功能将在第二次被阻塞(预期结果为0字节)。任何人都可以解释一下吗? THX