Make sure the reader

The code below reads everything that needs to be read from the tcp client stream, and at the next iteration it will just sit there in Read () (I assume I'm waiting for data). How can I guarantee that this is not the case and just comes back when there is nothing to read? Should I set a low timeout and respond to an exception when it fails? Or is there a better way?

TcpClient tcpclnt = new TcpClient();
tcpclnt.Connect(ip, port);

Stream stm = tcpclnt.GetStream();

stm.Write(cmdBuffer, 0, cmdBuffer.Length);

byte[] response = new Byte[2048];

MemoryStream ms = new MemoryStream();
byte[] buffer = new Byte[2048];
int length;
while ((length = stm.Read(buffer, 0, buffer.Length)) > 0)
    ms.Write(buffer, 0, length);

byte[] response = ms.ToArray();


tcpclnt.Close();
+3
source share
4 answers

TcpClient has two properties that I would play with.

  • NoDelay Gets or sets a value that disables the delay when send or receive buffers are not full.
  • ReceiveTimeout , TcpClient .
+1

, . , .

+1

Is there a "Keep Connections Alive" on the server?

I had servers that send you a stream of empty bytes if you request them.

Enabling "Keep Connections Alive" stopped its execution.

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

Source: https://habr.com/ru/post/1707874/


All Articles