Corbee
Corbee

Reputation: 1009

How to improve this TCP code?

There are times that the recByte will fail to receive response even though the server did reply because the server wasn't fast enough. Which if happened I use

catch (System.IO.IOException ioe)

to prevent the error, but are there possible alternatives that allow the client to wait a bit longer? I did try

clientStream.ReadTimeout = 20000;

but it didn't work

TcpClient Client = new TcpClient();
Client.Connect(ipaddress, portnum);

NetworkStream clientStream = Client.GetStream();

byte[] buffer = themessagetosent;
clientStream.Write(buffer, 0, buffer.Length);

byte[] recByte = theresponse;
clientStream.Read(recByte, 0, recByte.Length);

Upvotes: 1

Views: 1214

Answers (3)

user90150
user90150

Reputation:

If the server sends very fewer bytes, you could consider using socket.NoDelay = false at the server end (also at client side if required), this disable the Nagle algorithm and force the tcp/ip stack to send the data immediately without looking for further data to collect.

CanRead and DataAvailable are used good at when you have dedicated thread to handle the socket and data read.

Upvotes: 1

Alex Aza
Alex Aza

Reputation: 78447

You need to increase timeout for the tcpClient, not for the stream. Also, probably want to increase timeout for both send and receive, and probably to more than just 2 sec.

var client = new TcpClient { SendTimeout = 10000, ReceiveTimeout = 10000 };

I believe if you look at inner exception in IOException, you will see SocketException inside. Look at error code to find out what exactly is happening.

Upvotes: 1

Will A
Will A

Reputation: 24988

Check out the use of CanRead and DataAvailable in this example on MSDN.

Upvotes: 0

Related Questions