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.

67 lines
2.2 KiB

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