DeliveryServer.cs 6.3 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218
  1. using System;
  2. using System.Collections.Concurrent;
  3. using System.Collections.Generic;
  4. using System.Linq;
  5. using Sers.Core.CL.MessageDelivery;
  6. using Vit.Core.Module.Log;
  7. using Vit.Extensions;
  8. using ZeroMQ;
  9. namespace Sers.CL.ClrZmq.ThreadWait
  10. {
  11. public class DeliveryServer : IDeliveryServer
  12. {
  13. public Sers.Core.Util.StreamSecurity.SecurityManager securityManager;
  14. public Action<IDeliveryConnection> Conn_OnDisconnected { private get; set; }
  15. public Action<IDeliveryConnection> Conn_OnConnected { private get; set; }
  16. /// <summary>
  17. /// connGuid -> conn
  18. /// </summary>
  19. public readonly ConcurrentDictionary<long, DeliveryConnection> connMap = new ConcurrentDictionary<long, DeliveryConnection>();
  20. public IEnumerable<IDeliveryConnection> ConnectedList => connMap.Values.Select(conn => ((IDeliveryConnection)conn));
  21. /// <summary>
  22. /// 地址。例如: "tcp://*:4502" 、 "ipc://4502"
  23. /// </summary>
  24. public string endpoint = "tcp://*:4502";
  25. SocketPoller poller = new SocketPoller();
  26. #region Start
  27. /// <summary>
  28. /// 启动服务
  29. /// </summary>
  30. public bool Start()
  31. {
  32. try
  33. {
  34. Logger.Info("[CL.DeliveryServer] Zmq.ThreadWait,starting... endpoint: \"" + endpoint + "\"");
  35. //(x.1) create zmq conn
  36. var socket = new ZSocket(ZSocketType.ROUTER);
  37. socket.Bind(endpoint);
  38. //(x.2) init poller
  39. poller.OnReceiveMessage = Zmq_OnReceiveMessage;
  40. poller.Start(socket);
  41. Logger.Info("[CL.DeliveryServer] Zmq.ThreadWait,started.");
  42. return true;
  43. }
  44. catch (Exception ex)
  45. {
  46. Logger.Error(ex);
  47. }
  48. return false;
  49. }
  50. void Zmq_OnReceiveMessage(ZMessage msg)
  51. {
  52. long connGuid;
  53. byte[] msgFrame;
  54. #region (x.1) get identity and msgFrame
  55. using (msg)
  56. {
  57. if (null == msg || msg.Count < 2) return;
  58. connGuid = msg[0].ReadInt64();
  59. msgFrame = msg[1].Read();
  60. #region 检测是否为 关闭命令
  61. if (msg.Count > 2)
  62. {
  63. bool getedCloseSignal = false;
  64. try
  65. {
  66. var data = msg[2].Read();
  67. if (data.Length > 0 && data[0] == 0xff)
  68. {
  69. getedCloseSignal = true;
  70. }
  71. }
  72. catch (Exception ex)
  73. {
  74. Logger.Error(ex);
  75. getedCloseSignal = true;
  76. }
  77. if (getedCloseSignal)
  78. {
  79. if (connMap.TryGetValue(connGuid, out var _conn))
  80. {
  81. _conn.Close();
  82. }
  83. else
  84. {
  85. SendCloseSignal(connGuid.Int64ToBytes());
  86. }
  87. return;
  88. }
  89. }
  90. #endregion
  91. }
  92. #endregion
  93. #region (x.2) get or create conn
  94. if (!connMap.TryGetValue(connGuid, out var conn))
  95. {
  96. //新连接
  97. conn=Delivery_OnConnected(connGuid);
  98. }
  99. #endregion
  100. #region (x.3)
  101. conn.OnGetFrame(conn, new ArraySegment<byte>(msgFrame));
  102. #endregion
  103. }
  104. void Zmq_SendFrameAsync(DeliveryConnection conn, byte[] data)
  105. {
  106. poller.SendMessageAsync(new ZMessage() { new ZFrame(conn.zmqIdentity), new ZFrame(data) });
  107. }
  108. #endregion
  109. #region Stop
  110. /// <summary>
  111. /// 停止服务
  112. /// </summary>
  113. public void Stop()
  114. {
  115. Logger.Info("[ServerMq] Zmq.ThreadWait,stop...");
  116. //(x.1) stop conn
  117. ConnectedList.ToList().ForEach(Delivery_OnDisconnected);
  118. connMap.Clear();
  119. //(x.2)
  120. poller.Close();
  121. Logger.Info("[ServerMq] Zmq.ThreadWait,stoped");
  122. }
  123. #endregion
  124. #region Delivery_Event
  125. private DeliveryConnection Delivery_OnConnected(long connGuid)
  126. {
  127. var conn = new DeliveryConnection() { zmqIdentity = connGuid.Int64ToBytes() };
  128. conn.securityManager = securityManager?.Clone();
  129. conn.OnSendFrameAsync = Zmq_SendFrameAsync;
  130. conn.Conn_OnDisconnected = Delivery_OnDisconnected;
  131. try
  132. {
  133. if (connMap.TryAdd(connGuid, conn))
  134. Conn_OnConnected?.Invoke(conn);
  135. }
  136. catch (Exception ex)
  137. {
  138. Logger.Error(ex);
  139. }
  140. return conn;
  141. }
  142. private void Delivery_OnDisconnected(IDeliveryConnection _conn)
  143. {
  144. var conn = (DeliveryConnection)_conn;
  145. SendCloseSignal(conn.zmqIdentity);
  146. connMap.TryRemove(conn.zmqIdentity.BytesToInt64(), out _);
  147. try
  148. {
  149. Conn_OnDisconnected?.Invoke(_conn);
  150. }
  151. catch (Exception ex)
  152. {
  153. Logger.Error(ex);
  154. }
  155. }
  156. private void SendCloseSignal(byte[] zmqIdentity)
  157. {
  158. try
  159. {
  160. if (poller != null)
  161. {
  162. poller.SendMessageAsync(new ZMessage() { new ZFrame(zmqIdentity), new ZFrame(new byte[1]), new ZFrame(new byte[] { (byte)0xff }) });
  163. poller.SendMessageAsync(new ZMessage() { new ZFrame(zmqIdentity), new ZFrame(new byte[1]), new ZFrame(new byte[] { (byte)0xff }) });
  164. }
  165. }
  166. catch (Exception ex)
  167. {
  168. Logger.Error(ex);
  169. }
  170. }
  171. #endregion
  172. }
  173. }