Receiving and sending data in C#

前端 未结 2 1166
面向向阳花
面向向阳花 2021-02-09 20:52

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

2条回答
  •  粉色の甜心
    2021-02-09 21:21

    Several problems here:

    1. 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.
    2. Poll() takes microseconds. Waiting 0.02ms for incoming data is likely to return false unless the data is there before you call Poll().
    3. You create a new StreamReader on every iteration, which might discard data already read in the previous one.

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

提交回复
热议问题