Răsfoiți Sursa

重构了C# enet封装, 增加ESocket类 api类似.net socket类

tanghai 12 ani în urmă
părinte
comite
8e4682f8f9

+ 8 - 7
CSharp/App/BossClient/BossClient.cs

@@ -10,26 +10,26 @@ namespace BossClient
 	{
 		private int sessionId;
 
-		private readonly ClientHost clientHost = new ClientHost();
+		private readonly IOService ioService = new IOService();
 
 		public BossClient()
 		{
-			this.clientHost.EnableCrc();
+			this.ioService.EnableCrc();
 		}
 
 		public void Dispose()
 		{
-			this.clientHost.Dispose();
+			this.ioService.Dispose();
 		}
 
 		public void RunOnce()
 		{
-			this.clientHost.RunOnce();
+			this.ioService.RunOnce();
 		}
 
 		public void Start(int timeout)
 		{
-			this.clientHost.Start(timeout);
+			this.ioService.Start(timeout);
 		}
 
 		public GateSession GateSession { get; private set; }
@@ -50,8 +50,9 @@ namespace BossClient
 			}
 
 			// 登录gate
-			Peer peer = await this.clientHost.ConnectAsync(realmInfo.Item1, realmInfo.Item2);
-			this.GateSession = new GateSession(loginSessionId, new ENetChannel(peer));
+			var eSocket = new ESocket(this.ioService);
+			await eSocket.ConnectAsync(realmInfo.Item1, realmInfo.Item2);
+			this.GateSession = new GateSession(loginSessionId, new ENetChannel(eSocket));
 			await this.GateSession.Login(realmInfo.Item3);
 		}
 	}

+ 21 - 24
CSharp/App/BossClient/ENetChannel.cs

@@ -9,17 +9,17 @@ namespace BossClient
 {
 	class ENetChannel: IMessageChannel
 	{
-		private readonly Peer peer;
+		private readonly ESocket eSocket;
 
-		public ENetChannel(Peer peer)
+		public ENetChannel(ESocket eSocket)
 		{
-			this.peer = peer;
+			this.eSocket = eSocket;
 		}
 
 		public async void Dispose()
 		{
-			await this.peer.DisconnectLaterAsync();
-			this.peer.Dispose();
+			await this.eSocket.DisconnectLaterAsync();
+			this.eSocket.Dispose();
 		}
 
 		public void SendMessage<T>(ushort opcode, T message, byte channelID = 0)
@@ -30,30 +30,27 @@ namespace BossClient
 			var opcodeBytes = BitConverter.GetBytes(opcode);
 			opcodeBytes.CopyTo(neworkBytes, 0);
 			protoBytes.CopyTo(neworkBytes, sizeof(ushort));
-			this.peer.WriteAsync(channelID, neworkBytes);
+			this.eSocket.WriteAsync(neworkBytes, channelID);
 		}
 
 		public async Task<Tuple<ushort, byte[]>> RecvMessage()
 		{
-			using (Packet packet = await this.peer.ReadAsync())
+			var bytes = await this.eSocket.ReadAsync();
+			const int opcodeSize = sizeof(ushort);
+			ushort opcode = BitConverter.ToUInt16(bytes, 0);
+			byte flag = bytes[2];
+			if (flag == 0)
 			{
-				byte[] bytes = packet.Bytes;
-				const int opcodeSize = sizeof(ushort);
-				ushort opcode = BitConverter.ToUInt16(bytes, 0);
-				byte flag = bytes[2];
-				if (flag == 0)
-				{
-					var messageBytes = new byte[packet.Length - opcodeSize - 1];
-					Array.Copy(bytes, opcodeSize + 1, messageBytes, 0, messageBytes.Length);
-					return Tuple.Create(opcode, messageBytes);
-				}
-				else
-				{
-					var messageBytes = new byte[packet.Length - opcodeSize - 5];
-					Array.Copy(bytes, opcodeSize + 5, messageBytes, 0, messageBytes.Length);
-					messageBytes = ZlibStream.UncompressBuffer(messageBytes);
-					return Tuple.Create(opcode, messageBytes);
-				}
+				var messageBytes = new byte[bytes.Length - opcodeSize - 1];
+				Array.Copy(bytes, opcodeSize + 1, messageBytes, 0, messageBytes.Length);
+				return Tuple.Create(opcode, messageBytes);
+			}
+			else
+			{
+				var messageBytes = new byte[bytes.Length - opcodeSize - 5];
+				Array.Copy(bytes, opcodeSize + 5, messageBytes, 0, messageBytes.Length);
+				messageBytes = ZlibStream.UncompressBuffer(messageBytes);
+				return Tuple.Create(opcode, messageBytes);
 			}
 		}
 	}

+ 3 - 0
CSharp/CSharp.sln

@@ -341,4 +341,7 @@ Global
 		{C4E7A34A-095C-4983-AB63-FC2D20CD6824} = {D0CC1FF4-2747-4278-A51F-BE9AA959175B}
 		{DD6F4735-E8E2-4F10-AE2B-434AB3A40236} = {D0CC1FF4-2747-4278-A51F-BE9AA959175B}
 	EndGlobalSection
+	GlobalSection(Performance) = preSolution
+		HasPerformanceSessions = true
+	EndGlobalSection
 EndGlobal

+ 0 - 115
CSharp/Platform/ENet/ClientHost.cs

@@ -1,115 +0,0 @@
-using System;
-using System.Threading.Tasks;
-using Log;
-
-namespace ENet
-{
-	public sealed class ClientHost: Host
-	{
-		public ClientHost(
-			uint peerLimit = NativeMethods.ENET_PROTOCOL_MAXIMUM_PEER_ID, uint channelLimit = 0,
-			uint incomingBandwidth = 0, uint outgoingBandwidth = 0)
-		{
-			if (peerLimit > NativeMethods.ENET_PROTOCOL_MAXIMUM_PEER_ID)
-			{
-				throw new ArgumentOutOfRangeException("peerLimit");
-			}
-			CheckChannelLimit(channelLimit);
-
-			this.host = NativeMethods.enet_host_create(
-				IntPtr.Zero, peerLimit, channelLimit, incomingBandwidth, outgoingBandwidth);
-
-			if (this.host == IntPtr.Zero)
-			{
-				throw new ENetException("Host creation call failed.");
-			}
-		}
-
-		public Task<Peer> ConnectAsync(string hostName, ushort port, 
-				uint channelLimit = NativeMethods.ENET_PROTOCOL_MAXIMUM_CHANNEL_COUNT,
-				uint data = 0)
-		{
-			CheckChannelLimit(channelLimit);
-
-			var tcs = new TaskCompletionSource<Peer>();
-			var address = new Address {HostName = hostName, Port = port};
-			ENetAddress nativeAddress = address.Struct;
-			IntPtr peerPtr = NativeMethods.enet_host_connect(
-				this.host, ref nativeAddress, channelLimit, data);
-			if (peerPtr == IntPtr.Zero)
-			{
-				throw new ENetException("Host connect call failed.");
-			}
-			var peer = new Peer(peerPtr);
-			this.PeersManager.Add(peerPtr, peer);
-			peer.PeerEvent.Connected += e => tcs.TrySetResult(peer);
-			return tcs.Task;
-		}
-
-		public void RunOnce(int timeout = 0)
-		{
-			this.OnEvents();
-
-			if (this.Service(timeout) < 0)
-			{
-				return;
-			}
-
-			while (true)
-			{
-				Event ev = this.GetEvent();
-				if (ev == null)
-				{
-					return;
-				}
-
-				switch (ev.Type)
-				{
-					case EventType.Connect:
-					{
-						var peer = this.PeersManager[ev.PeerPtr];
-						peer.PeerEvent.OnConnected(ev);
-						peer.PeerEvent.Connected = null;
-						break;
-					}
-					case EventType.Receive:
-					{
-						var peer = this.PeersManager[ev.PeerPtr];
-						peer.PeerEvent.OnReceived(ev);
-						peer.PeerEvent.Received = null;
-						break;
-					}
-					case EventType.Disconnect:
-					{
-						ev.EventState = EventState.DISCONNECTED;
-
-						var peer = this.PeersManager[ev.PeerPtr];
-						PeerEvent peerEvent = peer.PeerEvent;
-
-						this.PeersManager.Remove(peer.PeerPtr);
-						// enet_peer_disconnect会reset Peer,这里设置为0,防止再次Dispose
-						peer.PeerPtr = IntPtr.Zero;
-
-						if (peerEvent.Received != null)
-						{
-							peerEvent.OnReceived(ev);
-						}
-						else
-						{
-							peerEvent.OnDisconnect(ev);
-						}
-						break;
-					}
-				}
-			}
-		}
-
-		public void Start(int timeout = 0)
-		{
-			while (this.isRunning)
-			{
-				this.RunOnce(timeout);
-			}
-		}
-	}
-}

+ 3 - 5
CSharp/Platform/ENet/ENet.csproj

@@ -38,18 +38,16 @@
   </ItemGroup>
   <ItemGroup>
     <Compile Include="Address.cs" />
-    <Compile Include="ClientHost.cs" />
     <Compile Include="ENetException.cs" />
     <Compile Include="Event.cs" />
-    <Compile Include="Host.cs" />
+    <Compile Include="IOService.cs" />
     <Compile Include="Library.cs" />
     <Compile Include="NativeMethods.cs" />
-    <Compile Include="PeerEvent.cs" />
+    <Compile Include="ESocketEvent.cs" />
     <Compile Include="PeersManager.cs" />
     <Compile Include="NativeStructs.cs" />
     <Compile Include="Packet.cs" />
-    <Compile Include="Peer.cs" />
-    <Compile Include="ServerHost.cs" />
+    <Compile Include="ESocket.cs" />
   </ItemGroup>
   <ItemGroup>
     <Folder Include="Properties\" />

+ 55 - 18
CSharp/Platform/ENet/Peer.cs → CSharp/Platform/ENet/ESocket.cs

@@ -4,14 +4,15 @@ using System.Threading.Tasks;
 
 namespace ENet
 {
-	public sealed class Peer: IDisposable
+	public sealed class ESocket: IDisposable
 	{
-		private readonly PeerEvent peerEvent = new PeerEvent();
-		private IntPtr peerPtr;
+		private readonly ESocketEvent eSocketEvent = new ESocketEvent();
+		private IntPtr peerPtr = IntPtr.Zero;
+		private readonly IOService service;
 
-		public Peer(IntPtr peerPtr)
+		public ESocket(IOService service)
 		{
-			this.peerPtr = peerPtr;
+			this.service = service;
 		}
 
 		public void Dispose()
@@ -52,11 +53,11 @@ namespace ENet
 			}
 		}
 
-		public PeerEvent PeerEvent
+		public ESocketEvent ESocketEvent
 		{
 			get
 			{
-				return this.peerEvent;
+				return this.eSocketEvent;
 			}
 		}
 
@@ -82,30 +83,66 @@ namespace ENet
 			NativeMethods.enet_peer_throttle_configure(this.peerPtr, interval, acceleration, deceleration);
 		}
 
-		public void WriteAsync(byte channelID, byte[] data)
+		public Task<bool> ConnectAsync(
+			string hostName, ushort port,
+			uint channelLimit = NativeMethods.ENET_PROTOCOL_MAXIMUM_CHANNEL_COUNT,
+			uint data = 0)
 		{
-			var packet = new Packet(data);
-			this.WriteAsync(channelID, packet);
+			if (channelLimit > NativeMethods.ENET_PROTOCOL_MAXIMUM_CHANNEL_COUNT)
+			{
+				throw new ArgumentOutOfRangeException("channelLimit");
+			}
+
+			var tcs = new TaskCompletionSource<bool>();
+			var address = new Address { HostName = hostName, Port = port };
+			ENetAddress nativeAddress = address.Struct;
+			this.peerPtr = NativeMethods.enet_host_connect(
+				this.service.HostPtr, ref nativeAddress, channelLimit, data);
+			if (this.peerPtr == IntPtr.Zero)
+			{
+				throw new ENetException("Host connect call failed.");
+			}
+			this.service.PeersManager.Add(this.peerPtr, this);
+			this.ESocketEvent.Connected += e => tcs.TrySetResult(true);
+			return tcs.Task;
+		}
+
+		public Task<bool> AcceptAsync()
+		{
+			if (this.service.PeersManager.ContainsKey(IntPtr.Zero))
+			{
+				throw new ENetException("Do Not Accept Twice!");
+			}
+			var tcs = new TaskCompletionSource<bool>();
+			this.service.PeersManager.Add(this.PeerPtr, this);
+			this.ESocketEvent.Connected += e => tcs.TrySetResult(true);
+			return tcs.Task;
 		}
 
-		public void WriteAsync(byte channelID, Packet packet)
+		public void WriteAsync(byte[] data, byte channelID = 0, PacketFlags flags = PacketFlags.None)
 		{
+			var packet = new Packet(data, flags);
 			NativeMethods.enet_peer_send(this.peerPtr, channelID, packet.PacketPtr);
 			// enet_peer_send函数会自动删除packet,设置为0,防止Dispose或者析构函数再次删除
 			packet.PacketPtr = IntPtr.Zero;
 		}
 
-		public Task<Packet> ReadAsync()
+		public Task<byte[]> ReadAsync()
 		{
-			var tcs = new TaskCompletionSource<Packet>();
-			this.PeerEvent.Received += e =>
+			var tcs = new TaskCompletionSource<byte[]>();
+			this.ESocketEvent.Received += e =>
 			{
 				if (e.EventState == EventState.DISCONNECTED)
 				{
 					tcs.TrySetException(new ENetException("Peer Disconnected In Received"));
 				}
-				var packet = new Packet(e.PacketPtr);
-				tcs.TrySetResult(packet);
+
+				using (var packet = new Packet(e.PacketPtr))
+				{
+					var bytes = packet.Bytes;
+					packet.Dispose();
+					tcs.TrySetResult(bytes);
+				}
 			};
 			return tcs.Task;
 		}
@@ -114,7 +151,7 @@ namespace ENet
 		{
 			NativeMethods.enet_peer_disconnect(this.peerPtr, data);
 			var tcs = new TaskCompletionSource<bool>();
-			this.PeerEvent.Disconnect += e => tcs.TrySetResult(true);
+			this.ESocketEvent.Disconnect += e => tcs.TrySetResult(true);
 			return tcs.Task;
 		}
 
@@ -122,7 +159,7 @@ namespace ENet
 		{
 			NativeMethods.enet_peer_disconnect_later(this.peerPtr, data);
 			var tcs = new TaskCompletionSource<bool>();
-			this.PeerEvent.Disconnect += e => tcs.TrySetResult(true);
+			this.ESocketEvent.Disconnect += e => tcs.TrySetResult(true);
 			return tcs.Task;
 		}
 

+ 1 - 1
CSharp/Platform/ENet/PeerEvent.cs → CSharp/Platform/ENet/ESocketEvent.cs

@@ -2,7 +2,7 @@
 
 namespace ENet
 {
-	public class PeerEvent
+	public class ESocketEvent
 	{
 		private Action<Event> connected;
 		private Action<Event> received;

+ 0 - 153
CSharp/Platform/ENet/Host.cs

@@ -1,153 +0,0 @@
-using System;
-
-namespace ENet
-{
-	public abstract class Host: IDisposable
-	{
-		static Host()
-		{
-			Library.Initialize();
-		}
-
-		private readonly PeersManager peersManager = new PeersManager();
-
-		protected PeersManager PeersManager
-		{
-			get
-			{
-				return this.peersManager;
-			}
-		}
-
-		protected IntPtr host;
-		protected bool isRunning = true;
-		private readonly object eventsLock = new object();
-		private Action events;
-
-		~Host()
-		{
-			this.Dispose(false);
-		}
-
-		public virtual void Dispose()
-		{
-			this.Dispose(true);
-			GC.SuppressFinalize(this);
-		}
-
-		protected void Dispose(bool disposing)
-		{
-			if (this.host == IntPtr.Zero)
-			{
-				return;
-			}
-
-			NativeMethods.enet_host_destroy(this.host);
-
-			this.host = IntPtr.Zero;
-		}
-
-		public void EnableCrc()
-		{
-			NativeMethods.enet_enable_crc(this.host);
-		}
-
-		protected static void CheckChannelLimit(uint channelLimit)
-		{
-			if (channelLimit > NativeMethods.ENET_PROTOCOL_MAXIMUM_CHANNEL_COUNT)
-			{
-				throw new ArgumentOutOfRangeException("channelLimit");
-			}
-		}
-
-		protected Event GetEvent()
-		{
-			var enetEv = new ENetEvent();
-			int ret = NativeMethods.enet_host_check_events(this.host, enetEv);
-			if (ret <= 0)
-			{
-				return null;
-			}
-			var e = new Event(enetEv);
-			return e;
-		}
-
-		protected int Service(int timeout)
-		{
-			if (timeout < 0)
-			{
-				throw new ArgumentOutOfRangeException("timeout");
-			}
-			return NativeMethods.enet_host_service(this.host, null, (uint) timeout);
-		}
-
-		public void Broadcast(byte channelID, ref Packet packet)
-		{
-			NativeMethods.enet_host_broadcast(this.host, channelID, packet.PacketPtr);
-		}
-
-		public void CompressWithRangeCoder()
-		{
-			NativeMethods.enet_host_compress_with_range_coder(this.host);
-		}
-
-		public void DoNotCompress()
-		{
-			NativeMethods.enet_host_compress(this.host, IntPtr.Zero);
-		}
-
-		public void Flush()
-		{
-			NativeMethods.enet_host_flush(this.host);
-		}
-
-		public void SetBandwidthLimit(uint incomingBandwidth, uint outgoingBandwidth)
-		{
-			NativeMethods.enet_host_bandwidth_limit(this.host, incomingBandwidth, outgoingBandwidth);
-		}
-
-		public void SetChannelLimit(uint channelLimit)
-		{
-			CheckChannelLimit(channelLimit);
-			NativeMethods.enet_host_channel_limit(this.host, channelLimit);
-		}
-
-		public event Action Events
-		{
-			add
-			{
-				lock (this.eventsLock)
-				{
-					this.events += value;
-				}
-			}
-			remove
-			{
-				lock (this.eventsLock)
-				{
-					this.events -= value;
-				}
-			}
-		}
-
-		protected void OnEvents()
-		{
-			Action local = null;
-			lock (this.eventsLock)
-			{
-				if (this.events == null)
-				{
-					return;
-				}
-				local = this.events;
-				this.events = null;
-			}
-			local();
-		}
-
-		public void Stop()
-		{
-			this.isRunning = false;
-		}
-	}
-}

+ 291 - 0
CSharp/Platform/ENet/IOService.cs

@@ -0,0 +1,291 @@
+using System;
+
+namespace ENet
+{
+	public class IOService: IDisposable
+	{
+		static IOService()
+		{
+			Library.Initialize();
+		}
+
+		private readonly PeersManager peersManager = new PeersManager();
+
+		public PeersManager PeersManager
+		{
+			get
+			{
+				return this.peersManager;
+			}
+		}
+
+		protected IntPtr host;
+		protected bool isRunning = true;
+		private readonly object eventsLock = new object();
+		private Action events;
+
+		public IOService(string hostName, ushort port, 
+			uint peerLimit = NativeMethods.ENET_PROTOCOL_MAXIMUM_PEER_ID,
+			uint channelLimit = 0, 
+			uint incomingBandwidth = 0, 
+			uint outgoingBandwidth = 0)
+		{
+			if (peerLimit > NativeMethods.ENET_PROTOCOL_MAXIMUM_PEER_ID)
+			{
+				throw new ArgumentOutOfRangeException("peerLimit");
+			}
+
+			if (channelLimit > NativeMethods.ENET_PROTOCOL_MAXIMUM_CHANNEL_COUNT)
+			{
+				throw new ArgumentOutOfRangeException(string.Format("channelLimit: {0}", channelLimit));
+			}
+
+			var address = new Address { HostName = hostName, Port = port };
+			ENetAddress nativeAddress = address.Struct;
+			this.host = NativeMethods.enet_host_create(
+				ref nativeAddress, peerLimit, channelLimit, incomingBandwidth, 
+				outgoingBandwidth);
+
+			if (this.host == IntPtr.Zero)
+			{
+				throw new ENetException("Host creation call failed.");
+			}
+		}
+
+		public IOService(
+			uint peerLimit = NativeMethods.ENET_PROTOCOL_MAXIMUM_PEER_ID, 
+			uint channelLimit = 0,
+			uint incomingBandwidth = 0, 
+			uint outgoingBandwidth = 0)
+		{
+			if (peerLimit > NativeMethods.ENET_PROTOCOL_MAXIMUM_PEER_ID)
+			{
+				throw new ArgumentOutOfRangeException("peerLimit");
+			}
+
+			if (channelLimit > NativeMethods.ENET_PROTOCOL_MAXIMUM_CHANNEL_COUNT)
+			{
+				throw new ArgumentOutOfRangeException(string.Format("channelLimit: {0}", channelLimit));
+			}
+
+			this.host = NativeMethods.enet_host_create(
+				IntPtr.Zero, peerLimit, channelLimit, incomingBandwidth, outgoingBandwidth);
+
+			if (this.host == IntPtr.Zero)
+			{
+				throw new ENetException("Host creation call failed.");
+			}
+		}
+
+		~IOService()
+		{
+			this.Dispose(false);
+		}
+
+		public virtual void Dispose()
+		{
+			this.Dispose(true);
+			GC.SuppressFinalize(this);
+		}
+
+		protected void Dispose(bool disposing)
+		{
+			if (this.host == IntPtr.Zero)
+			{
+				return;
+			}
+
+			NativeMethods.enet_host_destroy(this.host);
+
+			this.host = IntPtr.Zero;
+		}
+
+		public IntPtr HostPtr
+		{
+			get
+			{
+				return this.host;
+			}
+		}
+
+		public void EnableCrc()
+		{
+			NativeMethods.enet_enable_crc(this.host);
+		}
+
+		private Event GetEvent()
+		{
+			var enetEv = new ENetEvent();
+			int ret = NativeMethods.enet_host_check_events(this.host, enetEv);
+			if (ret <= 0)
+			{
+				return null;
+			}
+			var e = new Event(enetEv);
+			return e;
+		}
+
+		public void CompressWithRangeCoder()
+		{
+			NativeMethods.enet_host_compress_with_range_coder(this.host);
+		}
+
+		public void DoNotCompress()
+		{
+			NativeMethods.enet_host_compress(this.host, IntPtr.Zero);
+		}
+
+		public void Flush()
+		{
+			NativeMethods.enet_host_flush(this.host);
+		}
+
+		public void SetBandwidthLimit(uint incomingBandwidth, uint outgoingBandwidth)
+		{
+			NativeMethods.enet_host_bandwidth_limit(this.host, incomingBandwidth, outgoingBandwidth);
+		}
+
+		public void SetChannelLimit(uint channelLimit)
+		{
+			if (channelLimit > NativeMethods.ENET_PROTOCOL_MAXIMUM_CHANNEL_COUNT)
+			{
+				throw new ArgumentOutOfRangeException(string.Format("channelLimit: {0}", channelLimit));
+			}
+			NativeMethods.enet_host_channel_limit(this.host, channelLimit);
+		}
+
+		public event Action Events
+		{
+			add
+			{
+				lock (this.eventsLock)
+				{
+					this.events += value;
+				}
+			}
+			remove
+			{
+				lock (this.eventsLock)
+				{
+					this.events -= value;
+				}
+			}
+		}
+
+		public void OnEvents()
+		{
+			Action local = null;
+			lock (this.eventsLock)
+			{
+				if (this.events == null)
+				{
+					return;
+				}
+				local = this.events;
+				this.events = null;
+			}
+			local();
+		}
+
+		public void Stop()
+		{
+			this.isRunning = false;
+		}
+
+		private int Service(int timeout)
+		{
+			if (timeout < 0)
+			{
+				throw new ArgumentOutOfRangeException(string.Format("timeout: {0}", timeout));
+			}
+			return NativeMethods.enet_host_service(this.host, null, (uint)timeout);
+		}
+
+		public void RunOnce(int timeout = 0)
+		{
+			if (timeout < 0)
+			{
+				throw new ArgumentOutOfRangeException(string.Format("timeout: {0}", timeout));
+			}
+
+			this.OnEvents();
+
+			if (this.Service(timeout) < 0)
+			{
+				return;
+			}
+
+			while (true)
+			{
+				Event ev = this.GetEvent();
+				if (ev == null)
+				{
+					return;
+				}
+
+				switch (ev.Type)
+				{
+					case EventType.Connect:
+					{
+						// 这是一个connect peer,否则是一个accept peer
+						if (this.PeersManager.ContainsKey(ev.PeerPtr))
+						{
+							var peer = this.PeersManager[ev.PeerPtr];
+							peer.ESocketEvent.OnConnected(ev);
+							peer.ESocketEvent.Connected = null;
+						}
+						else
+						{
+							var peer = this.PeersManager[IntPtr.Zero];
+
+							this.PeersManager.Remove(IntPtr.Zero);
+
+							peer.PeerPtr = ev.PeerPtr;
+							this.PeersManager.Add(peer.PeerPtr, peer);
+
+							peer.ESocketEvent.OnConnected(ev);
+							peer.ESocketEvent.Connected = null;
+						}
+						break;
+					}
+					case EventType.Receive:
+					{
+						var peer = this.PeersManager[ev.PeerPtr];
+						peer.ESocketEvent.OnReceived(ev);
+						peer.ESocketEvent.Received = null;
+						break;
+					}
+					case EventType.Disconnect:
+					{
+						ev.EventState = EventState.DISCONNECTED;
+
+						var peer = this.PeersManager[ev.PeerPtr];
+						ESocketEvent peerEvent = peer.ESocketEvent;
+
+						this.PeersManager.Remove(peer.PeerPtr);
+						// enet_peer_disconnect会reset Peer,这里设置为0,防止再次Dispose
+						peer.PeerPtr = IntPtr.Zero;
+
+						if (peerEvent.Received != null)
+						{
+							peerEvent.OnReceived(ev);
+						}
+						else
+						{
+							peerEvent.OnDisconnect(ev);
+						}
+						break;
+					}
+				}
+			}
+		}
+
+		public void Start(int timeout = 0)
+		{
+			while (this.isRunning)
+			{
+				this.RunOnce(timeout);
+			}
+		}
+	}
+}

+ 1 - 1
CSharp/Platform/ENet/Library.cs

@@ -1,6 +1,6 @@
 namespace ENet
 {
-	public static class Library
+	internal static class Library
 	{
 		public static void Initialize()
 		{

+ 1 - 1
CSharp/Platform/ENet/Packet.cs

@@ -3,7 +3,7 @@ using System.Runtime.InteropServices;
 
 namespace ENet
 {
-	public sealed class Packet: IDisposable
+	internal sealed class Packet: IDisposable
 	{
 		private IntPtr packet;
 

+ 4 - 4
CSharp/Platform/ENet/PeersManager.cs

@@ -5,11 +5,11 @@ namespace ENet
 {
 	public class PeersManager
 	{
-		private readonly Dictionary<IntPtr, Peer> peersManager = new Dictionary<IntPtr, Peer>();
+		private readonly Dictionary<IntPtr, ESocket> peersManager = new Dictionary<IntPtr, ESocket>();
 
-		public void Add(IntPtr peerPtr, Peer peer)
+		public void Add(IntPtr peerPtr, ESocket eSocket)
 		{
-			this.peersManager.Add(peerPtr, peer);
+			this.peersManager.Add(peerPtr, eSocket);
 		}
 
 		public void Remove(IntPtr peerPtr)
@@ -26,7 +26,7 @@ namespace ENet
 			return false;
 		}
 
-		public Peer this[IntPtr peerPtr]
+		public ESocket this[IntPtr peerPtr]
 		{
 			get
 			{

+ 0 - 115
CSharp/Platform/ENet/ServerHost.cs

@@ -1,115 +0,0 @@
-using System;
-using System.Threading.Tasks;
-
-namespace ENet
-{
-	public sealed class ServerHost: Host
-	{
-		public ServerHost(string hostName, ushort port, 
-			uint peerLimit = NativeMethods.ENET_PROTOCOL_MAXIMUM_PEER_ID,
-			uint channelLimit = 0, uint incomingBandwidth = 0, uint outgoingBandwidth = 0)
-		{
-			if (peerLimit > NativeMethods.ENET_PROTOCOL_MAXIMUM_PEER_ID)
-			{
-				throw new ArgumentOutOfRangeException("peerLimit");
-			}
-			CheckChannelLimit(channelLimit);
-
-			var address = new Address { HostName = hostName, Port = port };
-			ENetAddress nativeAddress = address.Struct;
-			this.host = NativeMethods.enet_host_create(
-				ref nativeAddress, peerLimit, channelLimit, incomingBandwidth, 
-				outgoingBandwidth);
-
-			if (this.host == IntPtr.Zero)
-			{
-				throw new ENetException("Host creation call failed.");
-			}
-		}
-
-		public Task<Peer> AcceptAsync()
-		{
-			if (this.PeersManager.ContainsKey(IntPtr.Zero))
-			{
-				throw new ENetException("Do Not Accept Twice!");
-			}
-			var tcs = new TaskCompletionSource<Peer>();
-			var peer = new Peer(IntPtr.Zero);
-			this.PeersManager.Add(peer.PeerPtr, peer);
-			peer.PeerEvent.Connected += e => tcs.TrySetResult(peer);
-			return tcs.Task;
-		}
-
-		public void RunOnce(int timeout = 0)
-		{
-			this.OnEvents();
-
-			if (this.Service(timeout) < 0)
-			{
-				return;
-			}
-
-			while (true)
-			{
-				Event ev = this.GetEvent();
-				if (ev == null)
-				{
-					return;
-				}
-
-				switch (ev.Type)
-				{
-					case EventType.Connect:
-					{
-						var peer = this.PeersManager[IntPtr.Zero];
-
-						this.PeersManager.Remove(IntPtr.Zero);
-
-						peer.PeerPtr = ev.PeerPtr;
-						this.PeersManager.Add(peer.PeerPtr, peer);
-
-						PeerEvent peerEvent = peer.PeerEvent;
-						peerEvent.OnConnected(ev);
-						break;
-					}
-					case EventType.Receive:
-					{
-						var peer = this.PeersManager[ev.PeerPtr];
-						peer.PeerEvent.OnReceived(ev);
-						peer.PeerEvent.Received = null;
-						break;
-					}
-					case EventType.Disconnect:
-					{
-						ev.EventState = EventState.DISCONNECTED;
-
-						var peer = this.PeersManager[ev.PeerPtr];
-						PeerEvent peerEvent = peer.PeerEvent;
-
-						this.PeersManager.Remove(ev.PeerPtr);
-						// enet_peer_disconnect 会 reset Peer,这里设置为0,防止再次Dispose
-						peer.PeerPtr = IntPtr.Zero;
-
-						if (peerEvent.Received != null)
-						{
-							peerEvent.OnReceived(ev);
-						}
-						else
-						{
-							peerEvent.OnDisconnect(ev);
-						}
-						break;
-					}
-				}
-			}
-		}
-
-		public void Start(int timeout = 0)
-		{
-			while (this.isRunning)
-			{
-				this.RunOnce(timeout);
-			}
-		}
-	}
-}

+ 27 - 37
CSharp/Platform/ENetTest/ENetClientServerTest.cs

@@ -9,51 +9,41 @@ namespace ENetCSTest
 	[TestClass]
 	public class ENetClientServerTest
 	{
-		private static async void ClientEvent(ClientHost host, string hostName, ushort port)
-		{
-			var peer = await host.ConnectAsync(hostName, port);
-			using (var sPacket = new Packet("0123456789".ToByteArray(), PacketFlags.Reliable))
-			{
-				peer.WriteAsync(0, sPacket);
-			}
-
-			using (var rPacket = await peer.ReadAsync())
-			{
-				Logger.Debug(rPacket.Bytes.ToHex());
-				CollectionAssert.AreEqual("9876543210".ToByteArray(), rPacket.Bytes);
-			}
-
-			await peer.DisconnectAsync();
-
-			host.Stop();
-		}
+		private static async void ClientEvent(IOService service, string hostName, ushort port)
+		{
+			var eSocket = new ESocket(service);
+			await eSocket.ConnectAsync(hostName, port);
+			eSocket.WriteAsync("0123456789".ToByteArray());
+
+			var bytes = await eSocket.ReadAsync();
+			CollectionAssert.AreEqual("9876543210".ToByteArray(), bytes);
+
+			await eSocket.DisconnectAsync();
 
-		private static async void ServerEvent(ServerHost host, Barrier barrier)
+			service.Stop();
+		}
+
+		private static async void ServerEvent(IOService service, Barrier barrier)
 		{
-			barrier.SignalAndWait();
-			var peer = await host.AcceptAsync();
-			// Client断开,Server端收到Disconnect事件,结束Server线程
-			peer.PeerEvent.Disconnect += ev => host.Stop();
-
-			using (var rPacket = await peer.ReadAsync())
-			{
-				Logger.Debug(rPacket.Bytes.ToHex());
-				CollectionAssert.AreEqual("0123456789".ToByteArray(), rPacket.Bytes);
-			}
-
-			using (var sPacket = new Packet("9876543210".ToByteArray(), PacketFlags.Reliable))
-			{
-				peer.WriteAsync(0, sPacket);
-			}
+			barrier.SignalAndWait();
+			var eSocket = new ESocket(service);
+			await eSocket.AcceptAsync();
+			// Client断开,Server端收到Disconnect事件,结束Server线程
+			eSocket.ESocketEvent.Disconnect += ev => service.Stop();
+
+			var bytes = await eSocket.ReadAsync();
+			CollectionAssert.AreEqual("0123456789".ToByteArray(), bytes);
+
+			eSocket.WriteAsync("9876543210".ToByteArray(), 0, PacketFlags.Reliable);
 		}
 
 		[TestMethod]
 		public void ClientSendToServer()
 		{
 			const string hostName = "127.0.0.1";
-			const ushort port = 8888;
-			var clientHost = new ClientHost();
-			var serverHost = new ServerHost(hostName, port);
+			const ushort port = 8888;
+			var clientHost = new IOService();
+			var serverHost = new IOService(hostName, port);
 
 			var serverThread = new Thread(() => serverHost.Start(10));
 			var clientThread = new Thread(() => clientHost.Start(10));