I have two processes communicating with each other over TCP sockets. Process A sends a request to process B and waits for a response. Process B handles the request, and sends a response. For some of the requests, it is not necessary to send a response back to process A.
Suppose process A first sends a request X that does not require a response, and immediately after that sends a request Y that does require a response, a noticeable small delay is observed when A is waiting for data on its socket (~0.04s). This is the flow of control:
A sends X
A sends Y
B handles X
B handles Y and writes response
(small delay in waitForReadyRead() in A of ~0.04s)
A receives response for Y
When I introduce a response for X as well, and let A wait for that response, the delay is gone, and the flow of control looks as follows:
A sends X
B handles X and writes response
A receives response for X
A sends Y
B handles Y and writes response
A receives response for Y
This is obviously some kind of synchronisation issue, but I cannot explain it. Can anyone explain the small delay that is induced in case B does not send a response for X?
This is the answer:
http://en.wikipedia.org/wiki/Nagle_algorithm
Your data is queued and not sent out. You need to set a socket option (TCP_NODELAY) to prevent this, or use some other transport protocol, like UDP. You can get more info in ‘man tcp’.