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 betweenA
andB
is established.B
is sitting idle and the idle timeout is reached.A
initiates the close- Before
B
receives theFIN
fromA
, it starts sending request toA
- After
B
sends the request, it will read the response
Since A
has already closed the connection, B
is not able to read.
My questions are
- Is this a possible situation ?
- How to handle idle timeout for clients?
- How to close the connection between
A
andB
properly (avoidB
sending request during the process). In short, how to close the connection atomically?
CodePudding user response:
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.
CodePudding user response:
How to close the connection between A and B properly (avoid B sending request during the process).
- Server detects timeout
- Server sends timeout detection message to the Client
- Server waits for a reply (if timeout, assume Client dead)
- if Client receives a timeout detection from the Server, it replies with ACK (or something like that)
- if Server receives an ACK from the Client, then 'gracefully' closes the connection
- from now on, neither the Server nor the Client should send/receive any messages (after sending the ACK, do not immediately close the connection from the client side, do linger for the agreed timeout - see setsockopt: SO_LINGER)
On top of that, like the other answers suggested, the Client should send a heartbeat if idle (to avoid timeout detections).