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 T开发者_Go百科cpClient();
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);
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.
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.
Check out the use of CanRead
and DataAvailable
in this example on MSDN.
精彩评论