UPoller.cs 6.5 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289
  1. using System;
  2. using System.Collections.Concurrent;
  3. using System.Collections.Generic;
  4. using System.Threading.Tasks;
  5. using Common.Base;
  6. using Common.Logger;
  7. namespace UNet
  8. {
  9. internal sealed class UPoller: IDisposable
  10. {
  11. static UPoller()
  12. {
  13. Library.Initialize();
  14. }
  15. private readonly USocketManager uSocketManager = new USocketManager();
  16. private readonly QueueDictionary<IntPtr, ENetEvent> connQueue = new QueueDictionary<IntPtr, ENetEvent>();
  17. private IntPtr host;
  18. private readonly USocket acceptor = new USocket(IntPtr.Zero);
  19. private readonly BlockingCollection<Action> blockingCollection = new BlockingCollection<Action>();
  20. private ENetEvent eNetEventCache;
  21. public UPoller(string hostName, ushort port)
  22. {
  23. UAddress address = new UAddress(hostName, port);
  24. ENetAddress nativeAddress = address.Struct;
  25. this.host = NativeMethods.EnetHostCreate(
  26. ref nativeAddress, NativeMethods.ENET_PROTOCOL_MAXIMUM_PEER_ID, 0, 0, 0);
  27. if (this.host == IntPtr.Zero)
  28. {
  29. throw new UException("Host creation call failed.");
  30. }
  31. NativeMethods.EnetHostCompressWithRangeCoder(this.host);
  32. }
  33. public UPoller()
  34. {
  35. this.host = NativeMethods.EnetHostCreate(
  36. IntPtr.Zero, NativeMethods.ENET_PROTOCOL_MAXIMUM_PEER_ID, 0, 0, 0);
  37. if (this.host == IntPtr.Zero)
  38. {
  39. throw new UException("Host creation call failed.");
  40. }
  41. }
  42. ~UPoller()
  43. {
  44. this.Dispose(false);
  45. }
  46. public void Dispose()
  47. {
  48. this.Dispose(true);
  49. GC.SuppressFinalize(this);
  50. }
  51. private void Dispose(bool disposing)
  52. {
  53. if (this.host == IntPtr.Zero)
  54. {
  55. return;
  56. }
  57. NativeMethods.EnetHostDestroy(this.host);
  58. this.host = IntPtr.Zero;
  59. }
  60. public Task<USocket> AcceptAsync()
  61. {
  62. if (this.uSocketManager.ContainsKey(IntPtr.Zero))
  63. {
  64. throw new UException("do not accept twice!");
  65. }
  66. var tcs = new TaskCompletionSource<USocket>();
  67. // 如果有请求连接缓存的包,从缓存中取
  68. if (this.connQueue.Count > 0)
  69. {
  70. IntPtr ptr = this.connQueue.FirstKey;
  71. this.connQueue.Remove(ptr);
  72. USocket socket = new USocket(ptr);
  73. this.uSocketManager.Add(ptr, socket);
  74. tcs.TrySetResult(socket);
  75. }
  76. else
  77. {
  78. this.uSocketManager.Add(acceptor.PeerPtr, acceptor);
  79. acceptor.Connected = eEvent =>
  80. {
  81. if (eEvent.Type == EventType.Disconnect)
  82. {
  83. tcs.TrySetException(new UException("socket disconnected in accpet"));
  84. }
  85. this.uSocketManager.Remove(IntPtr.Zero);
  86. USocket socket = new USocket(eEvent.Peer);
  87. this.uSocketManager.Add(socket.PeerPtr, socket);
  88. tcs.TrySetResult(socket);
  89. };
  90. }
  91. return tcs.Task;
  92. }
  93. public Task<USocket> ConnectAsync(string hostName, ushort port)
  94. {
  95. var tcs = new TaskCompletionSource<USocket>();
  96. UAddress address = new UAddress(hostName, port);
  97. ENetAddress nativeAddress = address.Struct;
  98. IntPtr ptr = NativeMethods.EnetHostConnect(
  99. this.host, ref nativeAddress, NativeMethods.ENET_PROTOCOL_MAXIMUM_CHANNEL_COUNT, 0);
  100. USocket socket = new USocket(ptr);
  101. if (socket.PeerPtr == IntPtr.Zero)
  102. {
  103. throw new UException("host connect call failed.");
  104. }
  105. this.uSocketManager.Add(socket.PeerPtr, socket);
  106. socket.Connected = eEvent =>
  107. {
  108. if (eEvent.Type == EventType.Disconnect)
  109. {
  110. tcs.TrySetException(new UException("socket disconnected in connect"));
  111. }
  112. tcs.TrySetResult(socket);
  113. };
  114. return tcs.Task;
  115. }
  116. private ENetEvent GetEvent()
  117. {
  118. if (this.eNetEventCache == null)
  119. {
  120. this.eNetEventCache = new ENetEvent();
  121. }
  122. if (NativeMethods.EnetHostCheckEvents(this.host, this.eNetEventCache) <= 0)
  123. {
  124. return null;
  125. }
  126. ENetEvent eNetEvent = this.eNetEventCache;
  127. this.eNetEventCache = null;
  128. return eNetEvent;
  129. }
  130. public void Flush()
  131. {
  132. NativeMethods.EnetHostFlush(this.host);
  133. }
  134. public void Add(Action action)
  135. {
  136. blockingCollection.Add(action);
  137. }
  138. private void OnEvents(int timeout)
  139. {
  140. // 处理读写线程的回调
  141. Action action;
  142. if (!this.blockingCollection.TryTake(out action, timeout))
  143. {
  144. return;
  145. }
  146. var queue = new Queue<Action>();
  147. queue.Enqueue(action);
  148. while (this.blockingCollection.TryTake(out action, 0))
  149. {
  150. queue.Enqueue(action);
  151. }
  152. while (queue.Count > 0)
  153. {
  154. Action a = queue.Dequeue();
  155. a();
  156. }
  157. }
  158. private int Service()
  159. {
  160. int ret = NativeMethods.EnetHostService(this.host, null, 0);
  161. return ret;
  162. }
  163. public void RunOnce(int timeout = 0)
  164. {
  165. if (timeout < 0)
  166. {
  167. throw new ArgumentOutOfRangeException(string.Format("timeout: {0}", timeout));
  168. }
  169. this.OnEvents(timeout);
  170. if (this.Service() < 0)
  171. {
  172. return;
  173. }
  174. while (true)
  175. {
  176. ENetEvent eNetEvent = this.GetEvent();
  177. if (eNetEvent == null)
  178. {
  179. return;
  180. }
  181. switch (eNetEvent.Type)
  182. {
  183. case EventType.Connect:
  184. {
  185. // 这是一个connect peer
  186. if (this.uSocketManager.ContainsKey(eNetEvent.Peer))
  187. {
  188. USocket uSocket = this.uSocketManager[eNetEvent.Peer];
  189. uSocket.OnConnected(eNetEvent);
  190. break;
  191. }
  192. // 这是accept peer
  193. if (this.uSocketManager.ContainsKey(IntPtr.Zero))
  194. {
  195. USocket uSocket = this.uSocketManager[IntPtr.Zero];
  196. uSocket.OnConnected(eNetEvent);
  197. break;
  198. }
  199. // 如果server端没有acceptasync,则请求放入队列
  200. this.connQueue.Add(eNetEvent.Peer, eNetEvent);
  201. break;
  202. }
  203. case EventType.Receive:
  204. {
  205. USocket uSocket = this.uSocketManager[eNetEvent.Peer];
  206. uSocket.OnReceived(eNetEvent);
  207. break;
  208. }
  209. case EventType.Disconnect:
  210. {
  211. // 如果链接还在缓存中,则删除
  212. if (this.connQueue.Remove(eNetEvent.Peer))
  213. {
  214. break;
  215. }
  216. // 链接已经被应用层接收
  217. USocket uSocket = this.uSocketManager[eNetEvent.Peer];
  218. this.uSocketManager.Remove(eNetEvent.Peer);
  219. // 等待的task将抛出异常
  220. if (uSocket.Connected != null)
  221. {
  222. uSocket.OnConnected(eNetEvent);
  223. break;
  224. }
  225. if (uSocket.Received != null)
  226. {
  227. uSocket.OnReceived(eNetEvent);
  228. break;
  229. }
  230. if (uSocket.Disconnect != null)
  231. {
  232. uSocket.OnDisconnect(eNetEvent);
  233. break;
  234. }
  235. break;
  236. }
  237. }
  238. }
  239. }
  240. public void Run(int timeout = 0)
  241. {
  242. while (true)
  243. {
  244. this.RunOnce(timeout);
  245. }
  246. }
  247. }
  248. }