NetworkStream.Read blocks

I am writing a simple application that will connect to the server. However, I also want to send simple chat commands (see Console.ReadLine below). However, this script will not reach string Message = Console.ReadLine(); , since it is locked in bytesRead = clientStream.Read(message, 0, 4096); .

I want to continue this script, but if it contains bytes, it must process them (as it does now), and if none of the bytes arrive, it must 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(); } 
+1
source share
1 answer

You can try using the DataAvailable property. He will tell you if there is anything in the outlet. If it is erroneous, do not make the Read call.

+5
source

All Articles