diff --git a/Apewer/Network/TcpClient.cs b/Apewer/Network/TcpClient.cs
index db7eac4..733a94a 100644
--- a/Apewer/Network/TcpClient.cs
+++ b/Apewer/Network/TcpClient.cs
@@ -72,38 +72,10 @@ namespace Apewer.Network
if (timeout < 1) throw new ArgumentOutOfRangeException(nameof(timeout));
_socket = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp);
- if (timeout > 0)
- {
- RuntimeUtility.InBackground(timeout, () =>
- {
- if (!_socket.Connected)
- {
- _socket.Close();
-#if !NET20
- _socket.Dispose();
-#endif
- }
- }, true);
- }
- try
- {
- _socket.Connect(endpoint);
- _socket.SendTimeout = 5000;
- LocalEndPoint = _socket.LocalEndPoint as IPEndPoint;
- RemoteEndPoint = endpoint;
- }
- catch (SocketException ex)
- {
- if (ex.SocketErrorCode == SocketError.NotSocket)
- {
- throw new SocketException((int)SocketError.TimedOut);
- }
- throw new Exception($"{ex.ErrorCode} {ex.SocketErrorCode}: {ex.Message}");
- }
- catch
- {
- throw;
- }
+ _socket.Connect(endpoint, timeout);
+ _socket.SendTimeout = 5000;
+ LocalEndPoint = _socket.LocalEndPoint as IPEndPoint;
+ RemoteEndPoint = endpoint;
}
/// 关闭连接,释放系统资源。
diff --git a/Apewer/NetworkUtility.cs b/Apewer/NetworkUtility.cs
index 717070f..d92984b 100644
--- a/Apewer/NetworkUtility.cs
+++ b/Apewer/NetworkUtility.cs
@@ -593,6 +593,48 @@ namespace Apewer
#region Socket
+ /// 发起连接。
+ /// 套接字。
+ /// 远程终结点。
+ /// 连接超时毫秒数。当达到指定时长,或达到系统默认时长时,将会发生超时异常。
+ ///
+ ///
+ public static void Connect(this Socket socket, IPEndPoint endpoint, int timeout)
+ {
+ if (socket == null) throw new ArgumentNullException(nameof(socket));
+ if (endpoint == null) throw new ArgumentNullException(nameof(endpoint));
+ if (timeout < 1) throw new ArgumentOutOfRangeException(nameof(timeout));
+
+ var connecting = true;
+ if (timeout > 0)
+ {
+ RuntimeUtility.InBackground(timeout, () =>
+ {
+ if (connecting && !socket.Connected)
+ {
+ socket.Close();
+#if !NET20
+ socket.Dispose();
+#endif
+ }
+ }, true);
+ }
+ try
+ {
+ socket.Connect(endpoint);
+ }
+ catch (SocketException ex)
+ {
+ if (ex.SocketErrorCode == SocketError.NotSocket)
+ {
+ throw new SocketException((int)SocketError.TimedOut);
+ }
+ // throw new Exception($"{ex.ErrorCode} {ex.SocketErrorCode}: {ex.Message}");
+ throw;
+ }
+ connecting = false;
+ }
+
/// 检查 Socket 在线状态。
///
///
@@ -601,7 +643,7 @@ namespace Apewer
{
if (socket == null) return false;
- var pending = socket.Poll(1000, System.Net.Sockets.SelectMode.SelectRead);
+ var pending = socket.Poll(1000, SelectMode.SelectRead);
var available = socket.Available;
var offline = pending && available == 0;
return !offline;