NW连接超时

NWConnection timeout

这是我第一次 post 到社区,所以请耐心等待 ;-)

我正在使用 Apples 网络框架建立到服务器的 TCP 连接。它像这样锁定:

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
        }
    })

serverAddress和serverPort由用户输入。我想测试连接。现在我的问题是,如果用户输入了无效的地址/端口组合(服务器不提供该服务)。我在准备状态中停留了很长时间。之后我进入等待阶段(错误消息 POSIXErrorCode: Operation timed out)。

有什么方法可以设置第一次连接过程的超时时间吗?

谢谢你的想法

您可以通过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
}()

触发超时事件时,.waiting状态会回调

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

引用自Developer Fourms