ESocket.cs 7.7 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307
  1. using System;
  2. using System.Collections.Generic;
  3. using System.Runtime.InteropServices;
  4. using System.Threading.Tasks;
  5. namespace ENet
  6. {
  7. public sealed class ESocket: IDisposable
  8. {
  9. private IntPtr peerPtr = IntPtr.Zero;
  10. private readonly EService service;
  11. private readonly LinkedList<byte[]> recvBuffer = new LinkedList<byte[]>();
  12. public Action<EEvent> Connected { get; set; }
  13. public Action<EEvent> Received { get; set; }
  14. public Action<EEvent> Disconnect { get; set; }
  15. public Action<int> Error { get; set; }
  16. public ESocket(EService service)
  17. {
  18. this.service = service;
  19. }
  20. public void Dispose()
  21. {
  22. if (this.peerPtr == IntPtr.Zero)
  23. {
  24. return;
  25. }
  26. NativeMethods.EnetPeerReset(this.peerPtr);
  27. this.peerPtr = IntPtr.Zero;
  28. }
  29. public IntPtr PeerPtr
  30. {
  31. get
  32. {
  33. return this.peerPtr;
  34. }
  35. set
  36. {
  37. this.peerPtr = value;
  38. }
  39. }
  40. private ENetPeer Struct
  41. {
  42. get
  43. {
  44. if (this.peerPtr == IntPtr.Zero)
  45. {
  46. return new ENetPeer();
  47. }
  48. return (ENetPeer) Marshal.PtrToStructure(this.peerPtr, typeof (ENetPeer));
  49. }
  50. set
  51. {
  52. Marshal.StructureToPtr(value, this.peerPtr, false);
  53. }
  54. }
  55. public PeerState State
  56. {
  57. get
  58. {
  59. if (this.peerPtr == IntPtr.Zero)
  60. {
  61. return PeerState.Uninitialized;
  62. }
  63. return this.Struct.State;
  64. }
  65. }
  66. public void Ping()
  67. {
  68. NativeMethods.EnetPeerPing(this.peerPtr);
  69. }
  70. public void ConfigureThrottle(uint interval, uint acceleration, uint deceleration)
  71. {
  72. NativeMethods.EnetPeerThrottleConfigure(this.peerPtr, interval, acceleration, deceleration);
  73. }
  74. public Task<bool> ConnectAsync(
  75. string hostName, ushort port,
  76. uint channelLimit = NativeMethods.ENET_PROTOCOL_MAXIMUM_CHANNEL_COUNT, uint data = 0)
  77. {
  78. if (channelLimit > NativeMethods.ENET_PROTOCOL_MAXIMUM_CHANNEL_COUNT)
  79. {
  80. throw new ArgumentOutOfRangeException("channelLimit");
  81. }
  82. var tcs = new TaskCompletionSource<bool>();
  83. var address = new Address { HostName = hostName, Port = port };
  84. ENetAddress nativeAddress = address.Struct;
  85. this.peerPtr = NativeMethods.EnetHostConnect(this.service.HostPtr, ref nativeAddress,
  86. channelLimit, data);
  87. if (this.peerPtr == IntPtr.Zero)
  88. {
  89. throw new EException("host connect call failed.");
  90. }
  91. this.service.PeersManager.Add(this.peerPtr, this);
  92. this.Connected = eEvent =>
  93. {
  94. if (eEvent.EventState == EventState.DISCONNECTED)
  95. {
  96. tcs.TrySetException(new EException("socket disconnected in connect"));
  97. }
  98. tcs.TrySetResult(true);
  99. };
  100. return tcs.Task;
  101. }
  102. public Task<bool> AcceptAsync()
  103. {
  104. if (this.service.PeersManager.ContainsKey(IntPtr.Zero))
  105. {
  106. throw new EException("do not accept twice!");
  107. }
  108. var tcs = new TaskCompletionSource<bool>();
  109. // 如果有请求连接缓存的包,从缓存中取
  110. if (this.service.ConnEEvents.Count > 0)
  111. {
  112. EEvent eEvent = this.service.ConnEEvents.First.Value;
  113. this.service.ConnEEvents.RemoveFirst();
  114. this.PeerPtr = eEvent.PeerPtr;
  115. this.service.PeersManager.Add(this.PeerPtr, this);
  116. tcs.TrySetResult(true);
  117. }
  118. else
  119. {
  120. this.service.PeersManager.Add(this.PeerPtr, this);
  121. this.Connected = eEvent =>
  122. {
  123. if (eEvent.EventState == EventState.DISCONNECTED)
  124. {
  125. tcs.TrySetException(new EException("socket disconnected in accpet"));
  126. }
  127. this.service.PeersManager.Remove(IntPtr.Zero);
  128. this.PeerPtr = eEvent.PeerPtr;
  129. this.service.PeersManager.Add(this.PeerPtr, this);
  130. tcs.TrySetResult(true);
  131. };
  132. }
  133. return tcs.Task;
  134. }
  135. public void WriteAsync(byte[] data, byte channelID = 0, PacketFlags flags = PacketFlags.Reliable)
  136. {
  137. var packet = new EPacket(data, flags);
  138. NativeMethods.EnetPeerSend(this.peerPtr, channelID, packet.PacketPtr);
  139. // enet_peer_send函数会自动删除packet,设置为0,防止Dispose或者析构函数再次删除
  140. packet.PacketPtr = IntPtr.Zero;
  141. }
  142. public Task<byte[]> ReadAsync()
  143. {
  144. var tcs = new TaskCompletionSource<byte[]>();
  145. // 如果有缓存的包,从缓存中取
  146. if (this.recvBuffer.Count > 0)
  147. {
  148. var bytes = this.recvBuffer.First.Value;
  149. this.recvBuffer.RemoveFirst();
  150. tcs.TrySetResult(bytes);
  151. }
  152. // 没有缓存封包,设置回调等待
  153. else
  154. {
  155. this.Received = eEvent =>
  156. {
  157. if (eEvent.EventState == EventState.DISCONNECTED)
  158. {
  159. tcs.TrySetException(new EException("socket disconnected in receive"));
  160. }
  161. using (var packet = new EPacket(eEvent.PacketPtr))
  162. {
  163. var bytes = packet.Bytes;
  164. tcs.TrySetResult(bytes);
  165. }
  166. };
  167. }
  168. return tcs.Task;
  169. }
  170. public void WriteAsync(
  171. Action<int> action, byte[] data, byte channelID = 0, PacketFlags flags = PacketFlags.Reliable)
  172. {
  173. var packet = new EPacket(data, flags);
  174. int ret = NativeMethods.EnetPeerSend(this.peerPtr, channelID, packet.PacketPtr);
  175. // enet_peer_send函数会自动删除packet,设置为0,防止Dispose或者析构函数再次删除
  176. packet.PacketPtr = IntPtr.Zero;
  177. action(ret);
  178. }
  179. public void ReadAsync(Action<byte[], int> action)
  180. {
  181. // 如果有缓存的包,从缓存中取
  182. if (this.recvBuffer.Count > 0)
  183. {
  184. var bytes = this.recvBuffer.First.Value;
  185. this.recvBuffer.RemoveFirst();
  186. action(bytes, 0);
  187. }
  188. // 没有缓存封包,设置回调等待
  189. else
  190. {
  191. this.Received = eEvent =>
  192. {
  193. if (eEvent.EventState == EventState.DISCONNECTED)
  194. {
  195. action(new byte[0], -1);
  196. }
  197. using (var packet = new EPacket(eEvent.PacketPtr))
  198. {
  199. var bytes = packet.Bytes;
  200. action(bytes, 0);
  201. }
  202. };
  203. }
  204. }
  205. public Task<bool> DisconnectAsync(uint data = 0)
  206. {
  207. NativeMethods.EnetPeerDisconnect(this.peerPtr, data);
  208. // EnetPeerDisconnect会reset Peer,这里设置为0,防止再次Dispose
  209. this.PeerPtr = IntPtr.Zero;
  210. var tcs = new TaskCompletionSource<bool>();
  211. this.Disconnect = eEvent => tcs.TrySetResult(true);
  212. return tcs.Task;
  213. }
  214. public Task<bool> DisconnectLaterAsync(uint data = 0)
  215. {
  216. NativeMethods.EnetPeerDisconnectLater(this.peerPtr, data);
  217. // EnetPeerDisconnect会reset Peer,这里设置为0,防止再次Dispose
  218. this.PeerPtr = IntPtr.Zero;
  219. var tcs = new TaskCompletionSource<bool>();
  220. this.Disconnect = eEvent => tcs.TrySetResult(true);
  221. return tcs.Task;
  222. }
  223. public void DisconnectNow(uint data)
  224. {
  225. NativeMethods.EnetPeerDisconnectNow(this.peerPtr, data);
  226. // EnetPeerDisconnect会reset Peer,这里设置为0,防止再次Dispose
  227. this.PeerPtr = IntPtr.Zero;
  228. }
  229. internal void OnConnected(EEvent eEvent)
  230. {
  231. if (this.Connected == null)
  232. {
  233. return;
  234. }
  235. Action<EEvent> localConnected = this.Connected;
  236. this.Connected = null;
  237. // 此调用将让await ConnectAsync返回,所以null必须在此之前设置
  238. localConnected(eEvent);
  239. }
  240. internal void OnReceived(EEvent eEvent)
  241. {
  242. // 如果应用层还未调用readasync则将包放到缓存队列
  243. if (this.Received == null)
  244. {
  245. using (var packet = new EPacket(eEvent.PacketPtr))
  246. {
  247. var bytes = packet.Bytes;
  248. this.recvBuffer.AddLast(bytes);
  249. }
  250. }
  251. else
  252. {
  253. Action<EEvent> localReceived = this.Received;
  254. this.Received = null;
  255. // 此调用将让await ReadAsync返回,所以null必须在此之前设置
  256. localReceived(eEvent);
  257. }
  258. }
  259. internal void OnDisconnect(EEvent eEvent)
  260. {
  261. if (this.Disconnect == null)
  262. {
  263. return;
  264. }
  265. this.Disconnect(eEvent);
  266. }
  267. internal void OnError(int errorCode)
  268. {
  269. if (this.Error == null)
  270. {
  271. return;
  272. }
  273. this.Error(errorCode);
  274. }
  275. }
  276. }