From d4dfd627a333773e5bb2ebe79c5e1abdf05aed69 Mon Sep 17 00:00:00 2001 From: wenzuhuai Date: Thu, 14 May 2026 20:45:53 +0800 Subject: [PATCH] =?UTF-8?q?fix:=20=E4=BC=98=E5=8C=96=E8=BF=9E=E6=8E=A5?= =?UTF-8?q?=E7=A8=B3=E5=AE=9A=E6=80=A7=20-=20ping=E9=98=88=E5=80=BC?= =?UTF-8?q?=E4=BB=8E>2=E9=99=8D=E4=B8=BA>1=E7=BC=A9=E7=9F=AD=E6=96=AD?= =?UTF-8?q?=E8=BF=9E=E6=A3=80=E6=B5=8B=E7=AA=97=E5=8F=A3=20-=20=E5=8D=95?= =?UTF-8?q?=E8=8A=82=E7=82=B9=E8=BF=9E=E6=8E=A5=E5=A2=9E=E5=8A=A08?= =?UTF-8?q?=E7=A7=92=E8=B6=85=E6=97=B6=E4=BF=9D=E6=8A=A4=E9=98=B2=E6=AD=A2?= =?UTF-8?q?TCP=E8=B6=85=E6=97=B6=E5=A0=86=E7=A7=AF?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- Sources/Nats/NatsConnection.swift | 27 ++++++++++++++++++++++++--- 1 file changed, 24 insertions(+), 3 deletions(-) diff --git a/Sources/Nats/NatsConnection.swift b/Sources/Nats/NatsConnection.swift index aea7752..f66f01d 100644 --- a/Sources/Nats/NatsConnection.swift +++ b/Sources/Nats/NatsConnection.swift @@ -305,12 +305,31 @@ class ConnectionHandler: ChannelInboundHandler { } do { - try await connectToServer(s: s) + // ⭐️ 单节点连接超时保护:8秒内连不上就跳过该节点 + // 防止 iOS 网络不可达时 TCP 超时堆积(默认30-75秒/节点) + try await withThrowingTaskGroup(of: Void.self) { group in + group.addTask { + try await self.connectToServer(s: s) + } + group.addTask { + try await Task.sleep(nanoseconds: 8_000_000_000) + throw NatsError.ConnectError.timeout + } + do { + try await group.next()! + } catch { + group.cancelAll() + throw error + } + group.cancelAll() + } + } catch is CancellationError { + throw CancellationError() } catch let error as NatsError.ConnectError { if case .invalidConfig(_) = error { throw error } - logger.debug("error connecting to server: \(error)") + logger.debug("error connecting to server (8s timeout): \(error)") lastErr = error continue } catch { @@ -847,7 +866,9 @@ class ConnectionHandler: ChannelInboundHandler { internal func sendPing(_ rttCommand: RttCommand? = nil) async { let pingsOut = self.outstandingPings.wrappingIncrementThenLoad( ordering: AtomicUpdateOrdering.relaxed) - if pingsOut > 2 { + if pingsOut > 1 { + // ⭐️ 从 > 2 改为 > 1:缩短断连检测窗口 + // 原杣2次ping无响应(~20秒)即判定断连,加快用户感知 handleDisconnect() return }