TCPClient.cs 2.6 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596
  1. using System;
  2. using System.Collections.Generic;
  3. using System.Linq;
  4. using System.Net;
  5. using System.Net.Sockets;
  6. using System.Text;
  7. namespace SKMC.Api.Common.Tcp
  8. {
  9. /// <summary>
  10. /// TCP Socket客户端
  11. /// </summary>
  12. public class TCPClient
  13. {
  14. static readonly ILogger log = LogFactory.Get();
  15. public int BufferSize { get; set; } = 1024 * 8;
  16. public string Address { get; set; } = "127.0.0.1";
  17. public int Port { get; set; }
  18. public int Timeout { get; set; } = 10000;
  19. public bool KeepAlived { get; set; }
  20. public bool Logged { get; set; } = true;
  21. private Socket clientSocket;
  22. public TCPClient(string address, int port)
  23. {
  24. Address = address;
  25. Port = port;
  26. }
  27. public void Connect()
  28. {
  29. clientSocket = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp);
  30. clientSocket.SetSocketOption(SocketOptionLevel.Socket, SocketOptionName.ReceiveTimeout, Timeout);
  31. clientSocket.Connect(new IPEndPoint(IPAddress.Parse(Address), Port));
  32. log.Debug($"已连接至 {Address}:{Port}");
  33. }
  34. public bool IsConnected(int millSeconds)
  35. {
  36. if (clientSocket == null) return false;
  37. //bool pollResult = clientSocket.Poll(1000 * millSeconds, SelectMode.SelectRead);
  38. //return pollResult && clientSocket.Available == 0;
  39. return true;
  40. }
  41. public void Close()
  42. {
  43. try
  44. {
  45. clientSocket.Shutdown(SocketShutdown.Both);
  46. clientSocket.Close();
  47. }
  48. catch (Exception e)
  49. {
  50. log.Error("Socket连接关闭异常", e);
  51. }
  52. }
  53. public void Clear()
  54. {
  55. if (clientSocket.Available > 0)
  56. {
  57. clientSocket.Receive(new byte[clientSocket.Available]);
  58. }
  59. }
  60. public void Send(string msg, bool logged = true)
  61. {
  62. clientSocket.Send(Encoding.ASCII.GetBytes(msg));
  63. if (Logged && logged) log.Debug($"已发送消息:\n{msg}");
  64. }
  65. public string Recevie(bool logged = true)
  66. {
  67. byte[] buffer = new byte[BufferSize];
  68. int length = clientSocket.Receive(buffer);
  69. string msg = Encoding.ASCII.GetString(buffer, 0, length);
  70. if (Logged && logged) log.Debug($"接收到消息:\n{msg}");
  71. return msg;
  72. }
  73. public override string ToString() => $"address: {Address}, port: {Port}, keepAlive: {KeepAlived}, timeout: {Timeout}";
  74. }
  75. }