在Tcp通信期间使用StreamReader

我正在尝试学习如何在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的流(可能包含一个特殊字符或它具有一个隐藏状态)是什么?

gdp2009 回答:在Tcp通信期间使用StreamReader

因此,当reader.ReadAsync返回0时,该代码将停止。

Stream.Read上文档的“备注”部分把握了何时发生这种情况的关键:

  

仅当流中没有更多数据并且不需要更多数据(例如关闭的套接字或文件末尾)时,Read才会返回0。

因此,由于基础流是TCP连接,因此在关闭TCP连接时ReadAsync将返回0(并且TakeCareOfTCPClient将返回)。连接的任何一侧都可以关闭连接。

本文链接:https://www.f2er.com/3107011.html

大家都在问