asynSocketServer.cs 7.7 KB

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