See this document: https://blog.stephencleary.com/2009/05/detection-of-half-open-dropped.html
From the above document, ranking from best to worst:
- Add a keepalive message to the application protocol framing (an empty message). Length-prefixed and delimited systems may send empty messages (e.g., a length prefix of “0 bytes” or a single “end delimiter”).
Advantages. The higher-level protocol (the actual messages) are not affected.
Disadvantages. This requires a change to the software on both sides of the connection, so it may not be an option if the application protocol is already specified and immutable.
- Add a keepalive message to the actual application protocol (a “null” message). This adds a new message to the application protocol: a “null” message that should just be ignored.
Advantages. This may be used if the application protocol uses a non-uniform message framing system. In this case, the first solution could not be used.
Disadvantages. (Same as the first solution) This requires a change to the software on both sides of the connection, so it may not be an option if the application protocol is already specified and immutable.
- Explicit timer assuming the worst. Have a timer and assume that the connection has been dropped when the timer expires (of course, the timer is reset each time data is transferred). This is the way HTTP servers work, if they support persistent connections.
Advantages. Does not require changes to the application protocol; in situations where the code on the remote side cannot be changed, the first two solutions cannot be used. Furthermore, this solution causes less network traffic; it is the only solution that does not involve sending out keepalive (i.e., “are you still there?”) packets.
Disadvantages. Depending on the protocol, this may cause a high number of valid connections to be dropped.
- Manipulate the TCP/IP keepalive packet settings. This is a highly controversial solution that has complex arguments for both pros and cons. It is discussed in depth in Stevens’ book, chapter 23. Essentially, this instructs the TCP/IP stack to send keepalive packets periodically on the application’s behalf.
Advantages. Once the code to set the keepalive parameters is working, there is nothing else that the application needs to change. The other solutions all have timer events that the application must respond to; this one is “set and forget”.
Disadvantages. RFC 1122, section 188.8.131.52 indicates that acknowledgements for TCP keepalives without data may not be transmitted reliably by routers; this may cause valid connections to be dropped. Furthermore, TCP/IP stacks are not required to support keepalives at all (and many embedded stacks do not), so this solution may not translate to other platforms.