From fa89562f9d052f9481b538f8ccf103fca11c00cd Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?=E8=8B=A5=E6=B1=9D=E6=A3=8B=E8=8C=97?= <505554090@qq.com> Date: Sat, 25 Oct 2025 13:56:58 +0800 Subject: [PATCH] =?UTF-8?q?=E5=8F=91=E5=B8=83=EF=BC=9A3.1.19?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- TouchSocketVersion.props | 2 +- .../Tcp/TcpClientBase_Precompile.cs | 25 +++++++++++++++++-- 2 files changed, 24 insertions(+), 3 deletions(-) diff --git a/TouchSocketVersion.props b/TouchSocketVersion.props index b755f78b5..be3d44992 100644 --- a/TouchSocketVersion.props +++ b/TouchSocketVersion.props @@ -1,7 +1,7 @@  - 3.1.18 + 3.1.19 $(BaseVersion) diff --git a/src/TouchSocket/Components/Tcp/TcpClientBase_Precompile.cs b/src/TouchSocket/Components/Tcp/TcpClientBase_Precompile.cs index a86ab21b0..a62c50c72 100644 --- a/src/TouchSocket/Components/Tcp/TcpClientBase_Precompile.cs +++ b/src/TouchSocket/Components/Tcp/TcpClientBase_Precompile.cs @@ -43,6 +43,8 @@ public partial class TcpClientBase this.ThrowIfConfigIsNull(); // 等待信号量,以控制并发连接 await this.m_semaphoreForConnect.WaitTimeAsync(millisecondsTimeout, token).ConfigureAwait(EasyTask.ContinueOnCapturedContext); + + Socket socket = null; try { // 如果已经在线,则无需再次连接 @@ -56,10 +58,11 @@ public partial class TcpClientBase // 释放之前的Socket资源 this.MainSocket.SafeDispose(); // 创建新的Socket连接 - var socket = this.CreateSocket(iPHost); + socket = this.CreateSocket(iPHost); // 触发连接前的事件 var args = new ConnectingEventArgs(); await this.PrivateOnTcpConnecting(args).ConfigureAwait(EasyTask.ContinueOnCapturedContext); + // 根据取消令牌决定是否支持异步取消 if (token.CanBeCanceled) { @@ -82,6 +85,7 @@ public partial class TcpClientBase } } } + // 更新在线状态 this.m_online = true; // 设置当前Socket @@ -101,6 +105,14 @@ public partial class TcpClientBase // 触发连接成功的事件 _ = EasyTask.SafeRun(this.PrivateOnTcpConnected, new ConnectedEventArgs(), this.m_tokenSourceForReceive.Token); } + catch + { + // 连接失败时确保Socket被释放 + socket?.SafeDispose(); + // 重置在线状态 + this.m_online = false; + throw; + } finally { // 释放信号量 @@ -124,6 +136,7 @@ public partial class TcpClientBase // 等待信号量,以确保同时只有一个连接操作 await this.m_semaphoreForConnect.WaitTimeAsync(millisecondsTimeout, token).ConfigureAwait(EasyTask.ContinueOnCapturedContext); + Socket socket = null; try { // 如果已经在线,则无需进行连接操作 @@ -136,7 +149,7 @@ public partial class TcpClientBase // 释放之前的Socket资源 this.MainSocket.SafeDispose(); // 创建新的Socket连接 - var socket = this.CreateSocket(iPHost); + socket = this.CreateSocket(iPHost); // 触发连接前的事件 await this.PrivateOnTcpConnecting(new ConnectingEventArgs()).ConfigureAwait(EasyTask.ContinueOnCapturedContext); // 异步开始连接 @@ -162,6 +175,14 @@ public partial class TcpClientBase // 启动新任务,处理连接后的操作 _ = EasyTask.SafeRun(this.PrivateOnTcpConnected, new ConnectedEventArgs(), this.m_tokenSourceForReceive.Token); } + catch + { + // 连接失败时确保Socket被释放 + socket?.SafeDispose(); + // 重置在线状态 + this.m_online = false; + throw; + } finally { // 释放信号量,允许其他连接操作