using System;
using System.Net;
using System.Net.Sockets;
namespace Apewer.Network
{
/// TCP 客户端。
public class TcpClient : IDisposable
{
Socket _socket = null;
/// 套接字实例。
public Socket Socket { get => _socket; }
/// 在线。
public bool Online { get => NetworkUtility.Online(_socket); }
/// 本地终结点。
public IPEndPoint LocalEndPoint { get; private set; }
/// 远程终结点。
public IPEndPoint RemoteEndPoint { get; private set; }
/// 启动客户端,并连接到服务端。
/// 远程 IP 地址。
/// 远程端口号。
///
///
///
public TcpClient(string ip, int port) : this(new IPEndPoint(IPAddress.Parse(ip), port), 0) { }
/// 启动客户端,并连接到服务端。
/// 远程 IP 地址。
/// 远程端口号。
/// 连接超时毫秒数。当达到指定时长,或达到系统默认时长时,将会发生超时异常。
///
///
///
public TcpClient(string ip, int port, int timeout) : this(new IPEndPoint(IPAddress.Parse(ip), port), timeout) { }
/// 启动客户端,并连接到服务端。
/// 远程 IP 地址。
/// 远程端口号。
///
///
///
public TcpClient(IPAddress ip, int port) : this(new IPEndPoint(ip, port), 0) { }
/// 启动客户端,并连接到服务端。
/// 远程 IP 地址。
/// 远程端口号。
/// 连接超时毫秒数。当达到指定时长,或达到系统默认时长时,将会发生超时异常。
///
///
///
public TcpClient(IPAddress ip, int port, int timeout) : this(new IPEndPoint(ip, port), timeout) { }
/// 启动客户端,并连接到服务端。
public TcpClient(IPEndPoint endpoint) : this(endpoint, 0) { }
/// 启动客户端,并连接到服务端。
/// 远程终结点。
/// 连接超时毫秒数。当达到指定时长,或达到系统默认时长时,将会发生超时异常。
///
///
///
public TcpClient(IPEndPoint endpoint, int timeout)
{
if (endpoint == null) throw new ArgumentNullException(nameof(endpoint));
if (timeout < 1) throw new ArgumentOutOfRangeException(nameof(timeout));
_socket = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp);
_socket.Connect(endpoint, timeout);
_socket.SendTimeout = 5000;
LocalEndPoint = _socket.LocalEndPoint as IPEndPoint;
RemoteEndPoint = endpoint;
}
/// 关闭连接,释放系统资源。
public void Dispose()
{
try { _socket.Disconnect(false); } catch { }
try { _socket.Close(100); } catch { }
#if !NET20
try { _socket.Dispose(); } catch { }
#endif
}
/// 接收。
///
///
///
///
///
public byte[] Receive(int maxLength = 1024) => _socket.Receive(maxLength);
/// 发送。
///
///
///
public void Send(byte[] data) => _socket.Send(data);
}
}