Reputation: 149
I have a server written in C
that closes the connection if the connection is sitting idle for a specific time. I have an issue (that rarely happens). Read is failing on the client side and it says Connection broken
. I suspect the server is closing the connection and the client is sending some data at the same time.
Consider the following scenario (A is server, B is the client)
B
initiates the connection and the connection between A
and B
is established.B
is sitting idle and the idle timeout is reached.A
initiates the closeB
receives the FIN
from A
, it starts sending request to A
B
sends the request, it will read the responseSince A
has already closed the connection, B
is not able to read.
My questions are
A
and B
properly (avoid B
sending request during the process). In short, how to close the connection atomically?Upvotes: 1
Views: 5863
Reputation: 5790
How to close the connection between A and B properly (avoid B sending request during the process).
On top of that, like the other answers suggested, the Client should send a heartbeat if idle (to avoid timeout detections).
Upvotes: 0
Reputation: 12590
By my only little more than rudimentary network experience... and assuming that you are talking about a connection-oriented connection like TCP/IP in contrary to UDP/IP that is connection-less.
Yes, of course. You cannot avoid it.
There are multiple ways to do it, but all of them include: Send something from the client before the server's timeout elapses. If the client has no data to send, let it send something like a "life sign". This could be an empty data message, it all depends on your application protocol. Or make the timeout as long as necessary, including some margin. Some protocol timeout only after 3 times of allowed idle time.
You cannot close the connection atomically, because client and server are separated. Each packet on the network needs some time to be transmitted, and both can start sending at the very same moment, the server its closing message, and the client a new data message. There is nothing that you can do about this.
You need to make the client handle this situation properly. For example, it can accept such a broken connection and interpret it as closed. You should have already some reaction, if the server closes the connection while the client is idle.
Upvotes: 3