Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
888 views
in Technique[技术] by (71.8m points)

c# - 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). However this script won't get to string Message = Console.ReadLine(); since it's blocked at 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();
            }
See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

You could try using the DataAvailable property. It'll tell you whether there's anything waiting on the socket. If it's false, don't do the Read call.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...