TCPClient.cs 2.7 KB

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