Hello everybody,
could you please help me with the following problem:
I'm using a TcpClient to connect to a server. When I send a message and
the server doesn't reply in time, I send the same message again until a
given number of loops is reached or the server sends a reply.
I do not want to wait infinitely for the server to reply, so I set a
ReceiveTimeout of 5 seconds.
The problem is, the ReceiveTimeout is only used for the first message I
send. The other calls just don't bother and return right away.
The code to do this looks as follows:
TcpClient tcpClient = new TcpClient(host, port);
try
{
tcpClient.SendTimeout = this.sendTimeout;
tcpClient.ReceiveTimeout = this.receiveTimeout;
byte[] buffer = Encoding.UTF8.GetBytes(clientMessage);
byte[] input = new byte[512];
NetworkStream stream = tcpClient.GetStream();
StringBuilder result = new StringBuilder();
for (int i = 0; i < retries; i++)
{
try
{
stream.Write(buffer, 0, buffer.Length);
do
{
int read = stream.Read(input, 0, input.Length);
result.Append(Encoding.UTF8.GetString(input, 0, read));
}
while (!result.ToString().Contains(CurrentLineEnding));
// Handle read result here...
}
catch
{
// Ignore Exception, read again
}
}
}
finally
{
tcpClient.Client.Shutdown(SocketShutdown.Both);
tcpClient.Client.Close();
tcpClient.Close();
}
Can someone please tell me how I can make sure that the client waits 5
seconds whenever I read? I've also tried setting the ReadTimeout for the
network stream without any luck. What am I missing?
Thanks
Thorsten
Ben Voigt - 15 Nov 2006 21:58 GMT
> Hello everybody,
>
[quoted text clipped - 9 lines]
> The problem is, the ReceiveTimeout is only used for the first message I
> send. The other calls just don't bother and return right away.
TCP has an ordered delivery guarantee... your second message can't be
processed on the server until your first message is received and processed
(it may wait in a driver buffer if the server supports selective
acknowledgement, or be discarded based on being received out of order).
If you are implementing retry yourself and thinking in terms of messages
rather than continuous sequences of bytes, perhaps you want datagrams (UDP,
not TCP).