简体   繁体   中英

Set timeout when reading NetworkStream with TcpClient

I implemented TCP client to connect to the server using TcpClient ( C# .NET 4 ):

// TCP client & Connection
TcpClient client = new TcpClient();
client.Connect(new IPEndPoint(IPAddress.Parse(IP), PORT));
NetworkStream clientStream = client.GetStream();

// Get message from remote server
byte[] incomingBuffer = new byte[1024];
Int32 bytes = clientStream.Read(incomingBuffer, 0, incomingBuffer.Length);
string problesWithThis = System.Text.Encoding.ASCII.GetString(incomingBuffer, 0, bytes);

Connection to server works well. But I can read only part of the answer from the server and undelivered part of the message is read at the next connection attempt .

I tried to set NetworkStream timeout:

// No change for me   
clientStream.ReadTimeout = 10000;

Then I tried to simulate timeout:

// This works well, the client has enough time to read the answers. But it's not the right solution.

// ....

NetworkStream clientStream = client.GetStream();
Thread.Sleep(TimeSpan.FromSeconds(1));

// Read stream ....

Data is transported over TCP in packets, which arrive serially (but not necessarily in the correct sequence). Immediately when data is available, ie when the logically (if not chronolgically) next packet is received, clientStream.Read() will return with the data in this (and maybe any other oo-sequence) packet(s) - no matter if this is all data the sending side has sent or not.

Your Thread.Sleep() makes the program wait for a second - in this time more than one packets arrive and are buffered on the system level, so the call to clientStream.Read() will return immediately with the available data.

The correct way to handle this is to loop your Read() until BytesAvailable() becomes zero or a complete application-layer protocol element is detected.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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