简体   繁体   English

networkStream.Read被阻止

[英]networkStream.Read is blocking

I'm writing a simple application which will connect with a server. 我正在编写一个将与服务器连接的简单应用程序。 However I want to send simple chat commands aswell (see Console.ReadLine below). 但是我也想发送简单的聊天命令(请参阅下面的Console.ReadLine )。 However this script won't get to string Message = Console.ReadLine(); 但是,此脚本不会到达string Message = Console.ReadLine(); since it's blocked at bytesRead = clientStream.Read(message, 0, 4096); 因为它被阻止在bytesRead = clientStream.Read(message, 0, 4096); .

I want to continue this script, but if there's bytes incoming, it should process them (like it's doing now) and if no bytes are incoming, it should go through the script and wait for user input). 我想继续执行此脚本,但是如果有字节输入,它应该对其进行处理(就像现在所做的那样),如果没有字节输入,则应该通过脚本并等待用户输入)。 How can this be achieved? 如何做到这一点?

        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();
            }

You could try using the DataAvailable property. 您可以尝试使用DataAvailable属性。 It'll tell you whether there's anything waiting on the socket. 它会告诉您套接字上是否有任何等待。 If it's false, don't do the Read call. 如果为假,请不要执行Read调用。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM