You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

68 lines
2.4 KiB

  1. using System;
  2. using System.Net;
  3. using System.Net.Sockets;
  4. namespace Apewer.Network
  5. {
  6. /// <summary>TCP 客户端。</summary>
  7. public class TcpClient : IDisposable
  8. {
  9. Socket _socket = null;
  10. /// <summary>套接字实例。</summary>
  11. public Socket Socket { get => _socket; }
  12. /// <summary>在线。</summary>
  13. public bool Online { get => Extensions.Online(_socket); }
  14. /// <summary>本地终结点。</summary>
  15. public IPEndPoint LocalEndPoint { get; private set; }
  16. /// <summary>远程终结点。</summary>
  17. public IPEndPoint RemoteEndPoint { get; private set; }
  18. /// <summary>启动客户端,并连接到服务端。</summary>
  19. public TcpClient(string ip, int port) : this(IPAddress.Parse(ip), port) { }
  20. /// <summary>启动客户端,并连接到服务端。</summary>
  21. public TcpClient(IPAddress address, int port) : this(new IPEndPoint(address, port)) { }
  22. /// <summary>启动客户端,并连接到服务端。</summary>
  23. public TcpClient(IPEndPoint endpoint)
  24. {
  25. _socket = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp);
  26. _socket.Connect(endpoint);
  27. _socket.SendTimeout = 5000;
  28. LocalEndPoint = _socket.LocalEndPoint as IPEndPoint;
  29. RemoteEndPoint = endpoint;
  30. }
  31. /// <summary>关闭连接,释放系统资源。</summary>
  32. public void Dispose()
  33. {
  34. try { _socket.Disconnect(false); } catch { }
  35. try { _socket.Close(100); } catch { }
  36. #if !NET20
  37. try { _socket.Dispose(); } catch { }
  38. #endif
  39. }
  40. /// <summary>接收。</summary>
  41. /// <exception cref="ArgumentNullException"></exception>
  42. /// <exception cref="ArgumentOutOfRangeException"></exception>
  43. /// <exception cref="SocketException"></exception>
  44. /// <exception cref="ObjectDisposedException"></exception>
  45. /// <exception cref="System.Security.SecurityException"></exception>
  46. public byte[] Receive(int maxLength = 1024) => _socket.Receive(maxLength);
  47. /// <summary>发送。</summary>
  48. /// <exception cref="ArgumentNullException" />
  49. /// <exception cref="SocketException" />
  50. /// <exception cref="ObjectDisposedException" />
  51. public void Send(byte[] data) => _socket.Send(data);
  52. }
  53. }