英文:
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)))
}
}
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。


评论