Ensure streamreader doesn't hang waiting for data

試著忘記壹切 提交于 2019-12-06 03:54:13

TcpClient has two properties that I would play with.

  1. NoDelay Gets or sets a value that disables a delay when send or receive buffers are not full.
  2. ReceiveTimeout Gets or sets the amount of time a TcpClient will wait to receive data once a read operation is initiated

Maybe you should use multithreading. One thread should wait for data, another should process received data.

Does the server have "Keep Connections Alive" on ?

I have had servers which will send you a stream of empty bytes as long as you request them.

Turning "Keep Connections Alive" stopped it doing this.

var socket = new System.Net.Sockets.TcpClient();
            socket.NoDelay = true;
            socket.Connect(uri.Host, port);
            var ns = socket.GetStream();
            int timeout = 500; //ms
            DateTime lastReceived = DateTime.Now;
            string buffer = "";
            while (true)
            {
                if (ns.DataAvailable)
                {
                    var b = ns.ReadByte();
                    buffer += b + ", "; //customise this line yourself
                    lastReceived = DateTime.Now;
                    continue;
                }
                if (lastReceived.AddMilliseconds(timeout) < DateTime.Now) break;
                System.Threading.Thread.Sleep(timeout / 5);
            }
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!