处理NWConnection超时

huangapple go评论237阅读模式
英文:

Handling NWConnection timeout

问题

stateUpdateHandler 函数再也没有被调用。在处理连接超时时,你可以执行以下操作:

// 当连接状态更新时,检查是否出现连接超时的错误
connection.stateUpdateHandler = { [self] newState in
    print("newState: \(newState)")
    
    if newState == .failed {
        if let error = connection.currentPath?.status {
            if case .satisfied = error {
                // 连接失败但错误状态为 "satisfied",这意味着连接超时
                print("Connection timed out.")
            } else {
                // 处理其他连接错误
                print("Connection error: \(error)")
            }
        }
    }
}

// 启动连接
connection.start(queue: .main)

这段代码将检查连接状态更新,并在连接失败时检查错误状态以判断是否是连接超时。如果是连接超时,它会打印 "Connection timed out." 消息。

英文:

How to handle a connection timing out?

let connection = NWConnection(to: endpoint, using: .tcp)
connection.stateUpdateHandler = { [self] newState in
    print("newState: \(newState)")
}
connection.start(queue: .main)

Log:

newState: preparing
nw_socket_handle_socket_event [C1.1.4.1:1] Socket SO_ERROR [60: Operation timed out]
... several more times

The stateUpdateHandler function is never called again.

答案1

得分: 0

NWConnection 中似乎没有实现超时功能,我们需要自己处理:

let connectionTimeout = 15
connection.start(queue: .main)

DispatchQueue.main.asyncAfter(deadline: .now() + .seconds(connectionTimeout)) { [weak self] in
        guard let self = self else { return }
        if self.connection.state != .ready {
            self.connection.stateUpdateHandler?(.failed(.posix(.ETIMEDOUT)))
        }
    }
英文:

It turns out NWConnection doesn't implement timeouts. We have to do it ourselves:

let connectionTimeout = 15
connection.start(queue: .main)

DispatchQueue.main.asyncAfter(deadline: .now() + .seconds(connectionTimeout)) { [weak self] in
        guard let self = self else { return }
        if self.connection.state != .ready {
            self.connection.stateUpdateHandler?(.failed(.posix(.ETIMEDOUT)))
        }
    }

huangapple
  • 本文由 发表于 2023年4月11日 07:00:27
  • 转载请务必保留本文链接:https://go.coder-hub.com/75981322.html
  • network-framework
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定