networkStream.Read 正在阻塞

本文关键字:Read networkStream | 更新日期: 2023-09-27 18:35:09

我正在编写一个简单的应用程序,它将与服务器连接。但是我也想发送简单的聊天命令(见下文Console.ReadLine)。但是,此脚本不会string Message = Console.ReadLine();,因为它在 bytesRead = clientStream.Read(message, 0, 4096); 处被阻止。

我想继续这个脚本,但如果有字节传入,它应该

处理它们(就像现在一样),如果没有字节传入,它应该通过脚本并等待用户输入)。如何实现这一点?

        TcpClient tcpClient = (TcpClient)client;
        NetworkStream clientStream = tcpClient.GetStream();
        byte[] message = new byte[4096];
        int bytesRead;
        while (true)
        {
            bytesRead = 0;
            try
            {
                // Blocks until a client sends a message                    
                bytesRead = clientStream.Read(message, 0, 4096);
            }
            catch (Exception)
            {
                // A socket error has occured
                break;
            }
            if (bytesRead == 0)
            {
                // The client has disconnected from the server
                break;
            }
            // Message has successfully been received
            ASCIIEncoding encoder = new ASCIIEncoding();
            // Output message
            Console.WriteLine("To: " + tcpClient.Client.LocalEndPoint);
            Console.WriteLine("From: " + tcpClient.Client.RemoteEndPoint);
            Console.WriteLine(encoder.GetString(message, 0, bytesRead));
            // Return message
            string Message = Console.ReadLine();
            if (Message != null)
            {
                byte[] buffer = encoder.GetBytes(Message);
                clientStream.Write(buffer, 0, buffer.Length);
                clientStream.Flush();
            }

networkStream.Read 正在阻塞

您可以尝试使用 DataAvailable 属性。它会告诉您插座上是否有任何东西在等待。如果它是假的,请不要执行Read调用。