您最多选择25个主题 主题必须以字母或数字开头,可以包含连字符 (-),并且长度不得超过35个字符

113 行
2.9 KiB

  1. #region << 版 本 注 释 >>
  2. /*----------------------------------------------------------------
  3. * 创建者:13118
  4. * 创建时间:2022/6/15 16:42:09
  5. * 版本:V1.0.0
  6. * 描述:
  7. *
  8. * ----------------------------------------------------------------
  9. * 修改人:
  10. * 时间:
  11. * 修改说明:
  12. *
  13. * 版本:V1.0.1
  14. *----------------------------------------------------------------*/
  15. #endregion << 版 本 注 释 >>
  16. using Polly;
  17. using Polly.Retry;
  18. using System;
  19. using System.Collections.Generic;
  20. using System.Linq;
  21. using System.Net;
  22. using System.Net.Sockets;
  23. using System.Text;
  24. using System.Threading;
  25. using System.Threading.Tasks;
  26. namespace ARI.EAP.HOST.Common
  27. {
  28. /// <summary>
  29. /// SocketClient 的摘要说明
  30. /// </summary>
  31. public class SocketClient
  32. {
  33. private static Socket socket;
  34. private Thread thread;
  35. private byte[] buffer = new byte[2048];
  36. private object sync_root = new object();
  37. static SocketClient()
  38. {
  39. socket = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp);
  40. }
  41. public SocketClient()
  42. {
  43. Task.Run(() => SocketConnect());
  44. }
  45. private void SocketConnect()
  46. {
  47. lock (sync_root)
  48. {
  49. RetryPolicy policy = Policy.Handle<SocketException>()
  50. .WaitAndRetryForever(retryAttempt => TimeSpan.FromSeconds(Math.Pow(2, retryAttempt)), (ex, time) =>
  51. {
  52. });// 永远等待并重试,每次等待2的指数次冥的时间
  53. policy.Execute(() =>
  54. {
  55. socket.Connect(new IPEndPoint(IPAddress.Parse("127.0.0.1"), int.Parse("10086")));
  56. thread = new Thread(StartReceive);
  57. thread.IsBackground = true;
  58. thread.Start(socket);
  59. });
  60. }
  61. }
  62. private void StartReceive(object obj)
  63. {
  64. string str;
  65. while (true)
  66. {
  67. Socket receiveSocket = obj as Socket;
  68. try
  69. {
  70. int result = receiveSocket.Receive(buffer);
  71. if (result == 0)
  72. {
  73. break;
  74. }
  75. else
  76. {
  77. str = Encoding.Default.GetString(buffer);
  78. }
  79. }
  80. catch (Exception ex)
  81. {
  82. }
  83. }
  84. }
  85. public void Disconnected()
  86. {
  87. try
  88. {
  89. socket.Shutdown(SocketShutdown.Both);
  90. socket.Close();
  91. thread.Abort();
  92. }
  93. catch (Exception ex)
  94. {
  95. }
  96. }
  97. public void SendMessage(string message)
  98. {
  99. socket.Send(Encoding.Default.GetBytes(message));
  100. }
  101. }
  102. }