Detecting connection timeout with NWConnection

Hi,


I'm working on a networking implementation that uses the Networking framework. I'm using NWListener/NWBrowser to advertise and discover services and have a working implementation to setup connections using NWConnection.


When one of both sides gracefully termininates a connection (NWConnection.cancel()) is detected by the other side. With a small test application I track the number of active connection which appears to match the number of expected connections.


I'm however having difficulties to detect an unintended network timeout, e.g. set device into flight mode, turn of Wifi, etc. At NWConnection level, I was expecting to receive a connection status change through NWConnection.stateUpdateHandler, but nothing happens.


To be more precise, a client (browser) is able to detect a timeout from a server (listener), but not vice versa. This results into a network implementation not able to detect client timeouts.


Of course I could implement a handshake/keepalive mechanism, but since NWConnection has tcp added to its stack, I was expecting to have any TCP timeouts to propagate into NWConnection and my handler being able to detect those timeouts.


I did some testing with the TicTacToe example app from WWDC 2019, which also does not seem to be able to recover from such an error.

- If two decvices are paired and in a game, killing one of the sides results into the game being cancelled

- If one of the devices instead goes into flight mode, the other side never detects it and keeps waiting forever


Any tips how to implement this timeout detection would be awesome, and/or if my expectations have been wrong.


Kind regards,

Remko Seelig

Accepted Answer

Meanwhile, I discovered that a timeout actually occurs, but it takes a very long (2-3minutes) before it is detected. I was convinced that I configured the TCP options properly, but after trying it again, I found out that the keepAlive settings for the TCP options actually DO work:


let tcpOptions = NWProtocolTCP.Options()
tcpOptions.enableKeepalive = true
tcpOptions.keepaliveIdle = 2
tcpOptions.keepaliveCount = 2
tcpOptions.keepaliveInterval = 2


Using settings above timeout is detected in about 5-6 seconds and of course can be modified by changing the appropriate values.

Detecting connection timeout with NWConnection
 
 
Q