TCP Half-Open Connections

Once the connection has been established, if no peer sends any data, then no packets are sent over the net. TCP is an idle protocol, so it assumes that the connection is active.

Disconnection reasons

  • Application closes: when a process is finished, usually sends a FIN packet which acknowledges the other peer that connection has been closed. But if a process crashes there is no guarantee that this packet will be sent to other peer.
  • Device Closes: if devices closes, most probably there won't be any notification about this.
  • Network cable unplugged: if network cable is unplugged it's the same that a router closes, there is no data being transferred so connection is not closed.
  • Loss signal from router: if application loses signal from router, connection will still be alive.

Detect Half-Open Disconnections 

You can try to detect disconnections using the following methods 

Second Connection

You can try to open a second connection and try to connect but this has some disadvantages, like you are consuming more resources, create new threads... and if other peer has rebooted, second connection will work but first won't.

Ping other peer

If you try to send a ping or whatever message with a half-open connection, you will see that you don't get any error.

Enable KeepAlive at TCP Socket level

A TCP keep-alive packet is simply an ACK with the sequence number set to one less than the current sequence number for the connection. A host receiving one of these ACKs responds with an ACK for the current sequence number. Keep-alives can be used to verify that the computer at the remote end of a connection is still available. TCP keep-alives can be sent once every TCPKeepAlive.Time (defaults to 7,200,000 milliseconds or two hours) if no other data or higher-level keep-alives have been carried over the TCP connection. If there is no response to a keep-alive, it is repeated once every TCPKeepAlive.Interval seconds. KeepAliveInterval defaults to 1000 milliseconds.

You can enable per-connection KeepAlive and allow that TCP protocol check if connection is active or not. This is the preferred method if you want to detect dropped disconnections (for example: when you unplug a network cable). From sgcWebSockets 4.3.7 you can enable TCPKeepAlive property to try to detect these half-open connections.

oClient := TsgcWebSocketClient.Create(nil);
oClient.TCPKeepAlive.Enabled := True;
oClient.TCPKeepAlive.Time := 3000;
oClient.TCPKeepAlive.Interval := 1000; 
Stay Informed

When you subscribe to the blog, we will send you an e-mail when there are new updates on the site so you wouldn't miss them.

sgcWebSockets 4.3.7
Telegram Client

Related Posts