ServerHost.cs 2.3 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116
  1. using System;
  2. using System.Threading.Tasks;
  3. using Log;
  4. namespace ENet
  5. {
  6. public sealed class ServerHost : Host
  7. {
  8. private Action<Event> acceptEvent;
  9. public ServerHost(Address address, uint peerLimit = NativeMethods.ENET_PROTOCOL_MAXIMUM_PEER_ID,
  10. uint channelLimit = 0, uint incomingBandwidth = 0,
  11. uint outgoingBandwidth = 0, bool enableCrc = true)
  12. {
  13. if (peerLimit > NativeMethods.ENET_PROTOCOL_MAXIMUM_PEER_ID)
  14. {
  15. throw new ArgumentOutOfRangeException("peerLimit");
  16. }
  17. CheckChannelLimit(channelLimit);
  18. ENetAddress nativeAddress = address.Struct;
  19. this.host = NativeMethods.enet_host_create(
  20. ref nativeAddress, peerLimit,
  21. channelLimit, incomingBandwidth, outgoingBandwidth);
  22. if (this.host == IntPtr.Zero)
  23. {
  24. throw new ENetException(0, "Host creation call failed.");
  25. }
  26. if (enableCrc)
  27. {
  28. NativeMethods.enet_enable_crc(this.host);
  29. }
  30. }
  31. public Task<Peer> AcceptAsync()
  32. {
  33. if (this.acceptEvent != null)
  34. {
  35. throw new ENetException(0, "don't accept twice, when last accept not return!");
  36. }
  37. var tcs = new TaskCompletionSource<Peer>();
  38. this.acceptEvent += e =>
  39. {
  40. var peer = new Peer(e.PeerPtr);
  41. this.PeersManager.Add(e.PeerPtr, peer);
  42. tcs.TrySetResult(peer);
  43. };
  44. return tcs.Task;
  45. }
  46. public void RunOnce(int timeout = 0)
  47. {
  48. this.OnExecuteEvents();
  49. if (this.Service(timeout) < 0)
  50. {
  51. return;
  52. }
  53. Event ev;
  54. while (this.CheckEvents(out ev) > 0)
  55. {
  56. switch (ev.Type)
  57. {
  58. case EventType.Connect:
  59. {
  60. if (this.acceptEvent != null)
  61. {
  62. this.acceptEvent(ev);
  63. this.acceptEvent = null;
  64. }
  65. break;
  66. }
  67. case EventType.Receive:
  68. {
  69. var peer = this.PeersManager[ev.PeerPtr];
  70. peer.PeerEvent.OnReceived(ev);
  71. peer.PeerEvent.Received = null;
  72. break;
  73. }
  74. case EventType.Disconnect:
  75. {
  76. ev.EventState = EventState.DISCONNECTED;
  77. var peer = this.PeersManager[ev.PeerPtr];
  78. PeerEvent peerEvent = peer.PeerEvent;
  79. this.PeersManager.Remove(ev.PeerPtr);
  80. peer.Dispose();
  81. if (peerEvent.Received != null)
  82. {
  83. peerEvent.OnReceived(ev);
  84. }
  85. else
  86. {
  87. peerEvent.OnDisconnect(ev);
  88. }
  89. break;
  90. }
  91. }
  92. }
  93. }
  94. public void Start(int timeout = 0)
  95. {
  96. while (isRunning)
  97. {
  98. RunOnce(timeout);
  99. }
  100. }
  101. }
  102. }