Search code examples
iosswiftnetwork-programmingtcp

NWConnection timeout


this is my first post to the community, so please be patient ;-)

I am using Apples Network framework to build a TCP connection to a server. It locks like this:

let testConnection = NWConnection(host: NWEndpoint.Host(server!.serverAddress), port: NWEndpoint.Port(server!.serverPort)!, using: .tcp)
testConnection.stateUpdateHandler = ({ state in
        print("TCP state change to: \(state)")
        switch state {
        case .setup:
            break
        case .waiting(let error):
            print("Waiting Error \(error)")
            testConnection.cancel()
            break
        case .preparing:
            break
        case .ready:
            beginCommunication()
            break
        case .failed(let error):
            print("\(error)")
            break
        case .cancelled:
            break
        default:
            break
        }
    })

The serverAddress and serverPort is entered by the user. I want to test the connection. Now my problem is, that if the user is entering an invalid address / port combination (the service is not offered by the server). I stuck in the preparing state for quite a long time. After that I get to the waiting stage (with error message POSIXErrorCode: Operation timed out).

Is there any way to set the timeout for this first connection process ?

Thanks for your ideas


Solution

  • You can set connection timed out by NWProtocolTCP.Options

    
    lazy var tcpOptions: NWProtocolTCP.Options = {
        let options = NWProtocolTCP.Options()
        options.connectionTimeout = 5 // connection timed out
        return options
    }()
    
    lazy var parames: NWParameters = {
        let parames = NWParameters(tls: nil, tcp: self.tcpOptions)
        if let isOption = parames.defaultProtocolStack.internetProtocol as? NWProtocolIP.Options {
            isOption.version = .v4
        }
        parames.preferNoProxies = true
        return parames
    }()
    
    lazy var connection: NWConnection = {
        let connection = NWConnection(host: "x.x.x.x", port: xxxx, using: self.parames)
        return connection
    }()
    
    

    When trigger the timed out event, the .waiting state will call back.

    2021-08-30 23:05:17.xxxxxx+xxxx Demo[xxxx:xxxxxx] [connection] nw_socket_handle_socket_event [C1:1] Socket SO_ERROR [60: Operation timed out]
    The connection is waiting for a network path change with: POSIXErrorCode: Operation timed out
    

    reference from Developer Fourms