views:

560

answers:

3

The code below reads everything there is to read from tcp client stream, and on the next iteration it will just sit there on the Read() (i'm assuming waiting for data). How can I ensure it doesn't and just returns when there's nothing there to read? Do I have to set low timeout, and respond to an exception when it fails out? Or there's 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();
A: 

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.

Saint Gerbil
tnx 4 reply. I can't change anything at the server. also, if I do set tcp client timeout to 1 sec it will timeout and throw the exception. so, no, i'm not getting empty bytes.
flamey
Have you tried adding break points or a counter to see if its hanging or just stuck in a loop ?
Saint Gerbil
its not stuck in a loop. its stuck on Read(). if I replace a loop with two consecutive stm.Read(buffer, 0, buffer.Length) lines, the first time it receives 20 bytes and goes over to the next line, and that's where it sits.or alternatively, if I make buffer size 10, it will iterate twice to get those 20 bytes, and then sit at the next, third, iteration.
flamey
A: 

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
Khadaji
I would think the correct answer should be (2):http://msdn.microsoft.com/en-us/library/system.net.sockets.tcpclient.receivetimeout.aspx
Andrew Y
+1  A: 

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

M. Jahedbozorgan