Joao Rocha

Joao Rocha

  • NA
  • 1
  • 0

Delay in TcpListener/TcpClient

Jun 7 2006 5:11 AM
Hi all!

I have an application (let's call it application C) running 4 TcpClient, each connected to a different application that runs a TcpListener (let's call them applications S1, S2, S3 and S4). All 5 applications run on localhost, and i'm using TcpListener/TcpClient for inter-process comunication.

At a certain point in my application C, i start sending plain text messages from C to S1, S2, S3 and S4, sequentially, and once every 100ms, aproximately. C sends messages using a StreamWriter WriteLine method, and S1, S2, S3 and S4 read those messages using a StreamReader ReadLine method. Sockets are in blocking mode.

Now, the problem is that the first time (and only the first time) that applications Sx read a message, SOME, but not all of the applications, MAY take a long time to actually read from the socket after it has been written to. I've made some benchmarking, and i've come up with something like this:

Message 1:
Sent to S1, second 0
Sent to S2, second 0.001
Sent to S3, second 0.002
Sent to S4, second 0.003
Received by S1, second 0.005
Received by S2, second 0.006
Received by S3, second 1.243
Received by S4, second 3.252


Notice that, although messages have been sent almost "simultaneously", some of the messages could not be read until a few seconds have passed. This does not happen if i try to address each of the Sx individually, only when i'm trying to reach all 4 of them.

After the first message, messages are sent once every 100ms, and they are "imediatly" acknowledged:

Message 2 to 3000:
Sent to S1, second 0
Sent to S2, second 0.001
Sent to S3, second 0.002
Sent to S4, second 0.003
Received by S1, second 0.005
Received by S2, second 0.006
Received by S3, second 0.007
Received by S4, second 0.008

With some more benchmarking, i found out that the first message can take up to 5.6 seconds to be read from the socket after it has been written to, while after the first message has gone through it usually takes even less than 1ms.

Now, i definitly need to work around that long delay when the first message is being passed. I've gone through all (?) of the properties of TcpListener, TcpClient, and the underlying Sockets and Streams, and still haven't figured it out.

One (possibly) important aspect is that this issue only happens in a multi-processor environment, and thus hasn't been reproduced in single processor machines (where the first message always takes less than 1ms to be read). This got me thinking about thread-safe issues, but the application is multi-process rather than multi-threaded, so i don't see a point there.

So, does anyone have a clue on why this might be happening and how can i fix it?

Thanks in advance :)

Joao.