I\'m still trying to improve a little bit what I wrote before. Now I faced a problem with receiving data. I have a program which I use to send string using tcpClient to a progr
Several problems here:
StreamReader
has a 4kB buffer and will try to read as much as possible in the first call to ReadLine()
. The result is that you might have data in the StreamReader and go into Poll() when there's no more data available because it's already been read.Poll()
takes microseconds. Waiting 0.02ms for incoming data is likely to return false unless the data is there before you call Poll()
.If you're just going to read lines and want a timeout and a StreamReader
, I would do something like:
delegate string ReadLineDelegate ();
...
using (NetworkStream networkStream = tcpClient.GetStream()) {
StreamReader reader = new StreamReader(networkStream);
ReadLineDelegate rl = new ReadLineDelegate (reader.ReadLine);
while (true) {
IAsyncResult ares = rl.BeginInvoke (null, null);
if (ares.AsyncWaitHandle.WaitOne (100) == false)
break; // stop after waiting 100ms
string str = rl.EndInvoke (ares);
if (str != null) {
Console.WriteLine ("Received: {0}", str);
send (str);
}
}
}