SocketClientWrapper.cs 5.8 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210
  1. using System;
  2. using System.Collections.Concurrent;
  3. using System.Collections.Generic;
  4. using System.Linq;
  5. using System.Net;
  6. using System.Net.Sockets;
  7. using System.Text;
  8. using System.Threading.Tasks;
  9. using System.Timers;
  10. namespace EPD.Data
  11. {
  12. public class SocketClientWrapper : IDisposable
  13. {
  14. public Action OnConnected;
  15. public Action OnDisconnected;
  16. public Action<byte[] /*data*/, int /*offset*/, int /*size*/> OnDataChanged;
  17. private static Object _lockerSender = new Object();
  18. private BlockingCollection<byte[]> SetPointCommandQueue = new BlockingCollection<byte[]>();
  19. Timer timer = new Timer(500);
  20. public class ClientStateObject
  21. {
  22. public const int BufferSize = 16384;
  23. public Socket WorkSocket = null;
  24. public byte[] CacheBufferByteData = new byte[BufferSize];
  25. }
  26. private Socket socket;
  27. public bool IsConnected { get { return socket != null && socket.Connected; } }
  28. public SocketClientWrapper()
  29. {
  30. timer.Elapsed += Timer_Elapsed;
  31. timer.Enabled = true;
  32. }
  33. private void Timer_Elapsed(object sender, ElapsedEventArgs e)
  34. {
  35. if (SetPointCommandQueue.Count > 0)
  36. {
  37. var byteData = SetPointCommandQueue.Take();
  38. socket.BeginSend(byteData, 0, byteData.Length, 0, new AsyncCallback(SendCallback), socket);
  39. }
  40. }
  41. ~SocketClientWrapper()
  42. {
  43. Dispose();
  44. }
  45. /// <summary>
  46. ///
  47. /// </summary>
  48. /// <param name="address">127.0.0.1:15000</param>
  49. public void Connect(string ip, int port)
  50. {
  51. try
  52. {
  53. var remote = new IPEndPoint(IPAddress.Parse(ip), port);
  54. Dispose();
  55. socket = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp);
  56. socket.BeginConnect(remote, ConnectCallback, socket);
  57. //Task.Run(() =>
  58. //{
  59. // while (SetPointCommandQueue.Count > 0)
  60. // {
  61. // System.Threading.Thread.Sleep(500);
  62. // }
  63. // System.Threading.Thread.Sleep(500);
  64. //});
  65. }
  66. catch (Exception ex)
  67. {
  68. System.Diagnostics.Trace.Write("Error in Connect, " + ex.Message);
  69. }
  70. }
  71. private void ConnectCallback(IAsyncResult ar)
  72. {
  73. try
  74. {
  75. var client = (Socket)ar.AsyncState;
  76. client.EndConnect(ar);
  77. if (OnConnected != null)
  78. OnConnected();
  79. System.Diagnostics.Trace.Write("Connected");
  80. var state = new ClientStateObject();
  81. state.WorkSocket = socket;
  82. socket.BeginReceive(state.CacheBufferByteData, 0, ClientStateObject.BufferSize, 0, ReceiveCallback, state);
  83. }
  84. catch (Exception ex)
  85. {
  86. System.Diagnostics.Trace.Write("Error in ConnectCallback, " + ex.Message);
  87. }
  88. }
  89. public void Disconnect()
  90. {
  91. Dispose();
  92. if (OnDisconnected != null)
  93. OnDisconnected();
  94. }
  95. private void ReceiveCallback(IAsyncResult ar)
  96. {
  97. try
  98. {
  99. if (!IsConnected)
  100. return;
  101. ClientStateObject state = (ClientStateObject)ar.AsyncState;
  102. Socket client = state.WorkSocket;
  103. int bytesRead = client.EndReceive(ar);
  104. if (bytesRead > 0)
  105. {
  106. if (OnDataChanged != null)
  107. OnDataChanged(state.CacheBufferByteData, 0, bytesRead);
  108. client.BeginReceive(state.CacheBufferByteData, 0, ClientStateObject.BufferSize, 0, new AsyncCallback(ReceiveCallback), state);
  109. }
  110. }
  111. catch (Exception ex)
  112. {
  113. System.Diagnostics.Trace.Write("Error in ReceiveCallback, " + ex.Message);
  114. Disconnect();
  115. }
  116. }
  117. public bool Send(byte[] byteData)
  118. {
  119. try
  120. {
  121. if (!IsConnected)
  122. return false;
  123. lock (_lockerSender)
  124. {
  125. SetPointCommandQueue.Add(byteData);
  126. //socket.BeginSend(byteData, 0, byteData.Length, 0, new AsyncCallback(SendCallback), socket);
  127. }
  128. return true;
  129. }
  130. catch (Exception ex)
  131. {
  132. System.Diagnostics.Trace.Write("Error int Write, " + ex.Message);
  133. }
  134. return false;
  135. }
  136. private void SendCallback(IAsyncResult ar)
  137. {
  138. try
  139. {
  140. lock (_lockerSender)
  141. {
  142. Socket client = (Socket)ar.AsyncState;
  143. client.EndSend(ar);
  144. }
  145. }
  146. catch (Exception ex)
  147. {
  148. System.Diagnostics.Trace.Write("Error in SendCallback, " + ex.Message);
  149. }
  150. }
  151. public void Dispose()
  152. {
  153. try
  154. {
  155. if (socket != null)
  156. {
  157. if (IsConnected)
  158. {
  159. socket.Shutdown(SocketShutdown.Both);
  160. }
  161. socket.Close();
  162. socket.Dispose();
  163. socket = null;
  164. }
  165. }
  166. catch (Exception ex)
  167. {
  168. System.Diagnostics.Trace.Write("Error in Dispose, " + ex.Message);
  169. }
  170. }
  171. }
  172. }