我正在尝试学习如何在C#中实现TCP通信,并且对StreamReader如何知道何时发件人不再发送数据感到困惑。
private async void TakeCareOfTCPClient(TcpClient paramClient)
{
NetworkStream stream = null;
StreamReader reader = null;
try
{
stream = paramClient.GetStream();
reader = new StreamReader(stream);
char[] buff = new char[64];
while (KeepRunning)
{
Debug.WriteLine("*** Ready to read");
int nRet = await reader.ReadAsync(buff,buff.Length);
System.Diagnostics.Debug.WriteLine("Returned: " + nRet);
if (nRet == 0)
{
Removeclient(paramClient); //This removes the client from a list containing
// all connected clients to the server.
System.Diagnostics.Debug.WriteLine("Socket disconnected");
break;
}
string receivedText = new string(buff);
System.Diagnostics.Debug.WriteLine("*** RECEIVED: " + receivedText);
Array.Clear(buff,buff.Length);
}
}
catch (Exception excp)
{
Removeclient(paramClient);
System.Diagnostics.Debug.WriteLine(excp.ToString());
}
}
让我们说客户端发送的消息正好是64个字符。但是,客户端不会断开与服务器的连接,可以在以后的时间发送另一条消息(假设消息之间传递了大量的时间)。调用此方法的服务器是否会因为客户端尚未发送另一条消息(即已读取0个字符)而立即尝试另一次读取并将客户端从其连接列表中删除?假设没有,那么导致服务器等待另一条消息而不返回0的流(可能包含一个特殊字符或它具有一个隐藏状态)是什么?