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, i.e. when the logically (if not chronolgically) next packet is received,
clientStream.Read()will return with the data in this (and maybe any other o-o-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 toclientStream.Read()will return immediately with the available data.The correct way to handle this is to loop your
Read()untilBytesAvailable()becomes zero or a complete application-layer protocol element is detected.