asynSocketServer.cs 7.2 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228
  1. using System;
  2. using System.Collections.Generic;
  3. using System.Linq;
  4. using System.Text;
  5. using System.Threading.Tasks;
  6. using System.Net;
  7. using System.Net.Sockets;
  8. using System.Threading;
  9. using Aitex.Core.RT.Event;
  10. using Aitex.Core.RT.Log;
  11. using MECF.Framework.Common.Equipment;
  12. namespace MECF.Framework.Common.Communications
  13. {
  14. public class AsynSocketServer : IDisposable
  15. {
  16. public delegate void ErrorHandler(string args);
  17. public event ErrorHandler OnErrorHappened;
  18. public delegate void MessageHandler(string message);
  19. public event MessageHandler OnDataChanged;
  20. public delegate void BinaryMessageHandler(byte[] message);
  21. public event BinaryMessageHandler OnBinaryDataChanged;
  22. private static Object _locker = new Object();
  23. public string NewLine { get; set; }
  24. public bool NeedLog { get; set; } = true;
  25. private string _ip;
  26. private int _port;
  27. private bool _isAscii;
  28. private static int _bufferSize = 1021;
  29. public bool IsConnected { get { return (_serverSocket != null /*&& _serverSocket.Connected*/); } }
  30. public AsynSocketServer(string ip, int port, bool isAscii,string newline = "\r")
  31. {
  32. _ip = ip;
  33. _port = port;
  34. _isAscii = isAscii;
  35. _serverSocket = null;
  36. NewLine = newline;
  37. }
  38. ~AsynSocketServer()
  39. {
  40. Dispose();
  41. }
  42. Socket _clientSocket;
  43. Socket _serverSocket;
  44. public void Start()
  45. {
  46. if (_serverSocket != null)
  47. return;
  48. //创建套接字
  49. IPEndPoint ipe = new IPEndPoint(IPAddress.Parse(_ip), _port);
  50. _serverSocket = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp);
  51. //绑定端口和IP
  52. _serverSocket.Bind(ipe);
  53. //设置监听
  54. _serverSocket.Listen(10);
  55. //连接客户端
  56. AsyncAccept(_serverSocket);
  57. }
  58. /// <summary>
  59. /// 连接到客户端
  60. /// </summary>
  61. /// <param name="serverSocket"></param>
  62. private void AsyncAccept(Socket serverSocket)
  63. {
  64. serverSocket.BeginAccept(asyncResult =>
  65. {
  66. //获取客户端套接字
  67. _clientSocket = serverSocket.EndAccept(asyncResult);
  68. LOG.Info(string.Format("Received client {0} connect request", _clientSocket.RemoteEndPoint));
  69. AsyncReveive();
  70. }, null);
  71. }
  72. byte[] _buffer;
  73. /// <summary>
  74. /// 接收消息
  75. /// </summary>
  76. /// <param name="client"></param>
  77. private void AsyncReveive()
  78. {
  79. _buffer = new byte[_bufferSize];
  80. try
  81. {
  82. //开始接收消息
  83. _clientSocket.BeginReceive(_buffer, 0, _buffer.Length, SocketFlags.None, new AsyncCallback(ReceiveCallback), null);
  84. }
  85. catch (Exception ex)
  86. {
  87. LOG.Write(ex);
  88. string reason = string.Format("TCP Socket recevice data failed:{0}", ex.Message);
  89. LOG.Error(string.Format("Communication {0}:{1:D} {2}.", _ip, _port, reason));
  90. OnErrorHappened(reason);
  91. }
  92. }
  93. private void ReceiveCallback(IAsyncResult asyncResult)
  94. {
  95. int length = _clientSocket.EndReceive(asyncResult);
  96. if(length > 0)
  97. {
  98. if (_isAscii)
  99. {
  100. string message = Encoding.ASCII.GetString(_buffer, 0, length);
  101. LOG.Info(string.Format("Client message:{0}", message));
  102. OnDataChanged(message);
  103. }
  104. else
  105. {
  106. byte[] recvBuff = new byte[length];
  107. for (int i = 0; i < length; i++)
  108. {
  109. recvBuff[i] = _buffer[i];
  110. }
  111. LOG.Info($"Client message: {string.Join(" ", recvBuff)}.");
  112. OnBinaryDataChanged(recvBuff);
  113. }
  114. }
  115. else
  116. {
  117. //client disconnect, will....
  118. }
  119. //清空数据,重新开始异步接收
  120. _buffer = new byte[_bufferSize];
  121. _clientSocket.BeginReceive(_buffer, 0, _buffer.Length, SocketFlags.None, new AsyncCallback(ReceiveCallback), _clientSocket);
  122. }
  123. /// <summary>
  124. /// 发送消息
  125. /// </summary>
  126. /// <param name="_clientSocket"></param>
  127. /// <param name="sendMessage"></param>
  128. public void Write(string sendMessage)
  129. {
  130. if (_clientSocket == null || sendMessage == string.Empty) return;
  131. //数据转码
  132. byte[] data = new byte[1024];
  133. data = Encoding.ASCII.GetBytes(sendMessage);
  134. try
  135. {
  136. //开始发送消息
  137. _clientSocket.BeginSend(data, 0, data.Length, SocketFlags.None, asyncResult =>
  138. {
  139. //完成消息发送
  140. int length = _clientSocket.EndSend(asyncResult);
  141. //输出消息
  142. LOG.Info(string.Format("Communication {0}:{1:D} Send {2}.", _ip, _port, data));
  143. }, null);
  144. }
  145. catch (Exception e)
  146. {
  147. LOG.Write(e);
  148. string reason = string.Format("TCP连接发生错误:{0}", e.Message);
  149. LOG.Error(string.Format("Communication {0}:{1:D} {2}.", _ip, _port, reason));
  150. OnErrorHappened(reason);
  151. }
  152. }
  153. public void Write(byte[] data)
  154. {
  155. if (_clientSocket == null || data.Count() == 0) return;
  156. try
  157. {
  158. //开始发送消息
  159. _clientSocket.BeginSend(data, 0, data.Length, SocketFlags.None, asyncResult =>
  160. {
  161. //完成消息发送
  162. int length = _clientSocket.EndSend(asyncResult);
  163. //输出消息
  164. LOG.Info(string.Format("Communication {0}:{1:D} Send {2}.", _ip, _port, data));
  165. }, null);
  166. }
  167. catch (Exception e)
  168. {
  169. LOG.Write(e);
  170. string reason = string.Format("TCP连接发生错误:{0}", e.Message);
  171. LOG.Error(string.Format("Communication {0}:{1:D} {2}.", _ip, _port, reason));
  172. OnErrorHappened(reason);
  173. }
  174. }
  175. /// </summary>
  176. public void Dispose()
  177. {
  178. try
  179. {
  180. if (_serverSocket != null)
  181. {
  182. if (IsConnected)
  183. {
  184. _serverSocket.Shutdown(SocketShutdown.Both);
  185. }
  186. _serverSocket.Close();
  187. _serverSocket.Dispose();
  188. _serverSocket = null;
  189. }
  190. }
  191. catch (Exception ex)
  192. {
  193. LOG.Write(ex);
  194. string reason = string.Format("释放socket资源失败:{0}", ex.Message);
  195. OnErrorHappened(reason);
  196. }
  197. }
  198. }
  199. }