From a93cab913d39492c99ff7f9abb4f58f48ad8fd2e Mon Sep 17 00:00:00 2001 From: Elivo Date: Thu, 31 Jul 2025 00:38:47 +0800 Subject: [PATCH] =?UTF-8?q?TcpClient=EF=BC=8C=E4=BF=AE=E6=94=B9=E4=BA=86?= =?UTF-8?q?=E5=8F=98=E9=87=8F=E7=9A=84=E5=90=8D=E7=A7=B0=E3=80=82?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- Apewer/Network/TcpClient.cs | 42 ++++++++++++++++++++----------------- 1 file changed, 23 insertions(+), 19 deletions(-) diff --git a/Apewer/Network/TcpClient.cs b/Apewer/Network/TcpClient.cs index 1e4031a..2aaacbe 100644 --- a/Apewer/Network/TcpClient.cs +++ b/Apewer/Network/TcpClient.cs @@ -1,13 +1,6 @@ -using Apewer; -using Apewer.Internals; -using System; -using System.Collections; -using System.Collections.Generic; -using System.IO; +using System; using System.Net; using System.Net.Sockets; -using System.Text; -using System.Threading; namespace Apewer.Network { @@ -16,13 +9,19 @@ namespace Apewer.Network public class TcpClient : IDisposable { - Socket _client = null; + Socket _socket = null; /// 套接字实例。 - public Socket Socket { get => _client; } + public Socket Socket { get => _socket; } + + /// 本地终结点。 + public IPEndPoint LocalEndPoint { get; private set; } + + /// 远程终结点。 + public IPEndPoint RemoteEndPoint { get; private set; } /// 已连接。 - public bool Connected { get => _client != null && _client.Connected; } + public bool Connected { get => _socket != null && _socket.Connected; } /// 启动客户端,并连接到服务端。 public TcpClient(string ip, int port) : this(IPAddress.Parse(ip), port) { } @@ -33,34 +32,39 @@ namespace Apewer.Network /// 启动客户端,并连接到服务端。 public TcpClient(IPEndPoint endpoint) { - _client = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp); - _client.Connect(endpoint); - _client.SendTimeout = 5000; + _socket = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp); + _socket.Connect(endpoint); + _socket.SendTimeout = 5000; + LocalEndPoint = _socket.LocalEndPoint as IPEndPoint; + RemoteEndPoint = endpoint; } /// 关闭连接,释放系统资源。 public void Dispose() { - try { _client.Disconnect(false); } catch { } - try { _client.Close(100); } catch { } + try { _socket.Disconnect(false); } catch { } + try { _socket.Close(100); } catch { } #if !NET20 - try { _client.Dispose(); } catch { } + try { _socket.Dispose(); } catch { } #endif } + /// 在线。 + public bool Online { get => Extensions.Online(_socket); } + /// 接收。 /// /// /// /// /// - public byte[] Receive(int maxLength = 1024) => _client.Receive(maxLength); + public byte[] Receive(int maxLength = 1024) => _socket.Receive(maxLength); /// 发送。 /// /// /// - public void Send(byte[] data) => _client.Send(data); + public void Send(byte[] data) => _socket.Send(data); }