networkStream.Read is blocking

c#

Solution

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.

Problem

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

Original source