Parcourir la source

服务端启用了enet_host_compress_with_range_coder,client端也必须调用该函数,否则client无法产生connect事件

tanghai il y a 13 ans
Parent
commit
805faabc18

+ 9 - 7
CSharp/App/LoginClient/ENetChannel.cs

@@ -36,13 +36,15 @@ namespace LoginClient
 
 		public async Task<Tuple<ushort, byte[]>> RecvMessage()
 		{
-			Packet packet = await this.peer.ReadAsync();
-			byte[] bytes = packet.Bytes;
-			const int opcodeSize = sizeof (ushort);
-			ushort opcode = BitConverter.ToUInt16(bytes, 0);
-			var messageBytes = new byte[packet.Length - opcodeSize];
-			Array.Copy(bytes, opcodeSize, messageBytes, 0, messageBytes.Length);
-			return Tuple.Create(opcode, messageBytes);
+			using (Packet packet = await this.peer.ReadAsync())
+			{
+				byte[] bytes = packet.Bytes;
+				const int opcodeSize = sizeof(ushort);
+				ushort opcode = BitConverter.ToUInt16(bytes, 0);
+				var messageBytes = new byte[packet.Length - opcodeSize];
+				Array.Copy(bytes, opcodeSize, messageBytes, 0, messageBytes.Length);
+				return Tuple.Create(opcode, messageBytes);
+			}
 		}
 	}
 }

+ 0 - 1
CSharp/App/LoginClient/GateSession.cs

@@ -57,7 +57,6 @@ namespace LoginClient
 			var result = await this.IMessageChannel.RecvMessage();
 			ushort opcode = result.Item1;
 			byte[] message = result.Item2;
-
 			if (opcode != MessageOpcode.SMSG_AUTH_CHALLENGE)
 			{
 				throw new LoginException(string.Format(

+ 4 - 14
CSharp/App/LoginClient/LoginClient.cs

@@ -34,29 +34,19 @@ namespace LoginClient
 			var tcpClient = new TcpClient();
 			await tcpClient.ConnectAsync(hostName, port);
 
-			Tuple<string, ushort, SRP6Client> realmInfo; // ip, port, K
-			var realmSession = new RealmSession(this.sessionId, new TcpChannel(tcpClient));
-			try
+			Tuple<string, ushort, SRP6Client> realmInfo = null; // ip, port, K
+			using (var realmSession = new RealmSession(this.sessionId, new TcpChannel(tcpClient)))
 			{
 				realmInfo = await realmSession.Login(account, password);
 				Logger.Trace("session: {0}, login success!", realmSession.ID);
 			}
-			finally
-			{
-				realmSession.Dispose();
-			}
 
 			// 登录gate
 			Peer peer = await this.clientHost.ConnectAsync(realmInfo.Item1, realmInfo.Item2);
-			var gateSession = new GateSession(this.sessionId, new ENetChannel(peer));
-			try
+			using (var gateSession = new GateSession(this.sessionId, new ENetChannel(peer)))
 			{
 				gateSession.Login(realmInfo.Item3);
 			}
-			finally
-			{
-				gateSession.Dispose();
-			}
-	    }
+		}
     }
 }

+ 16 - 5
CSharp/App/LoginClient/RealmSession.cs

@@ -40,9 +40,7 @@ namespace LoginClient
 
 			var smsgPasswordProtectType = 
 				ProtobufHelper.FromBytes<SMSG_Password_Protect_Type>(message);
-
-			Logger.Trace("message: {0}", JsonHelper.ToString(smsgPasswordProtectType));
-
+			
 			if (smsgPasswordProtectType.Code != 200)
 			{
 				throw new LoginException(string.Format(
@@ -139,8 +137,8 @@ namespace LoginClient
 				PasswordMd5 = passwordMd5Hex
 			};
 
-			Logger.Trace("account: {0}, password: {1}", 
-				cmsgAuthLogonPermit.Account, cmsgAuthLogonPermit.PasswordMd5.ToHex());
+			Logger.Trace("session: {0}, account: {1}, password: {2}", this.ID,
+				cmsgAuthLogonPermit.Account.ToStr(), cmsgAuthLogonPermit.PasswordMd5.ToHex());
 
 			this.MessageChannel.SendMessage(MessageOpcode.CMSG_AUTH_LOGON_PERMIT, cmsgAuthLogonPermit);
 			await this.Handle_CMSG_AuthLogonPermit_Response();
@@ -152,6 +150,8 @@ namespace LoginClient
 			var smsgAuthLogonChallengeResponse = 
 				await this.Handle_SMSG_Auth_Logon_Challenge_Response();
 
+			Logger.Trace("session: {0}, SMSG_Auth_Logon_Challenge_Response OK", this.ID);
+
 			// 以下是SRP6处理过程
 			var n = smsgAuthLogonChallengeResponse.N.ToUBigInteger();
 			var g = smsgAuthLogonChallengeResponse.G.ToUBigInteger();
@@ -180,13 +180,24 @@ namespace LoginClient
 			this.MessageChannel.SendMessage(MessageOpcode.CMSG_AUTH_LOGON_PROOF, cmsgAuthLogonProof);
 			await this.Handle_SMSG_Auth_Logon_Proof_M2();
 
+			Logger.Trace("session: {0}, SMSG_Auth_Logon_Proof_M2 OK", this.ID);
+
 			// 请求realm list
 			var cmsgRealmList = new CMSG_Realm_List();
 			this.MessageChannel.SendMessage(MessageOpcode.CMSG_REALM_LIST, cmsgRealmList);
 			var smsgRealmList = await this.Handle_SMSG_Realm_List();
 
+			Logger.Trace("session: {0}, SMSG_Realm_List OK", this.ID);
+
 			string address = smsgRealmList.GateList[0].Address.ToStr();
 			string[] split = address.Split(new[] { ':' });
+
+			if (split.Length != 2)
+			{
+				throw new LoginException(
+					string.Format("session: {0}, gate address error, address: {1}",
+					this.ID, address));
+			}
 			string gateIP = split[0];
 			ushort gatePort = UInt16.Parse(split[1]);
 			return Tuple.Create(gateIP, gatePort, srp6Client);

+ 1 - 0
CSharp/App/Modules/Robot/RobotViewModel.cs

@@ -106,6 +106,7 @@ namespace Modules.Robot
 
 		private void Disposing(bool disposing)
 		{
+			this.loginClient.Dispose();
 		}
 
 		public void Login()

+ 1 - 0
CSharp/CSharp.sln.DotSettings

@@ -10,6 +10,7 @@
 	<s:String x:Key="/Default/CodeInspection/Highlighting/InspectionSeverities/=ImplicitlyCapturedClosure/@EntryIndexedValue">DO_NOT_SHOW</s:String>
 	<s:String x:Key="/Default/CodeInspection/Highlighting/InspectionSeverities/=InconsistentNaming/@EntryIndexedValue">DO_NOT_SHOW</s:String>
 	<s:String x:Key="/Default/CodeInspection/Highlighting/InspectionSeverities/=LoopCanBeConvertedToQuery/@EntryIndexedValue">DO_NOT_SHOW</s:String>
+	<s:String x:Key="/Default/CodeInspection/Highlighting/InspectionSeverities/=PossibleNullReferenceException/@EntryIndexedValue">DO_NOT_SHOW</s:String>
 	<s:String x:Key="/Default/CodeInspection/Highlighting/InspectionSeverities/=RedundantAssignment/@EntryIndexedValue">DO_NOT_SHOW</s:String>
 	<s:String x:Key="/Default/CodeInspection/Highlighting/InspectionSeverities/=SuggestUseVarKeywordEverywhere/@EntryIndexedValue">DO_NOT_SHOW</s:String>
 	<s:String x:Key="/Default/CodeInspection/Highlighting/InspectionSeverities/=UnusedAutoPropertyAccessor_002EGlobal/@EntryIndexedValue">DO_NOT_SHOW</s:String>

+ 16 - 5
CSharp/Platform/ENet/ClientHost.cs

@@ -8,7 +8,8 @@ namespace ENet
 	{
 		public ClientHost(
 			uint peerLimit = NativeMethods.ENET_PROTOCOL_MAXIMUM_PEER_ID, uint channelLimit = 0,
-			uint incomingBandwidth = 0, uint outgoingBandwidth = 0, bool enableCrc = true)
+			uint incomingBandwidth = 0, uint outgoingBandwidth = 0, bool enableCrc = true,
+			bool compressWithRangeEncoder = true)
 		{
 			if (peerLimit > NativeMethods.ENET_PROTOCOL_MAXIMUM_PEER_ID)
 			{
@@ -21,13 +22,18 @@ namespace ENet
 
 			if (this.host == IntPtr.Zero)
 			{
-				throw new ENetException(0, "Host creation call failed.");
+				throw new ENetException("Host creation call failed.");
 			}
 
 			if (enableCrc)
 			{
 				this.EnableCrc();
 			}
+
+			if (compressWithRangeEncoder)
+			{
+				this.CompressWithRangeCoder();
+			}
 		}
 
 		public Task<Peer> ConnectAsync(string hostName, ushort port, 
@@ -43,7 +49,7 @@ namespace ENet
 				this.host, ref nativeAddress, channelLimit, data);
 			if (peerPtr == IntPtr.Zero)
 			{
-				throw new ENetException(0, "Host connect call failed.");
+				throw new ENetException("Host connect call failed.");
 			}
 			var peer = new Peer(peerPtr);
 			this.PeersManager.Add(peerPtr, peer);
@@ -60,9 +66,14 @@ namespace ENet
 				return;
 			}
 
-			Event ev;
-			while (this.CheckEvents(out ev) > 0)
+			while (true)
 			{
+				Event ev = this.GetEvent();
+				if (ev == null)
+				{
+					return;
+				}
+
 				switch (ev.Type)
 				{
 					case EventType.Connect:

+ 1 - 4
CSharp/Platform/ENet/ENetException.cs

@@ -4,11 +4,8 @@ namespace ENet
 {
 	public class ENetException: Exception
 	{
-		public ENetException(int code, string message): base(message)
+		public ENetException(string message): base(message)
 		{
-			this.Code = code;
 		}
-
-		public int Code { get; private set; }
 	}
 }

+ 9 - 5
CSharp/Platform/ENet/Host.cs

@@ -60,12 +60,16 @@ namespace ENet
 			}
 		}
 
-		protected int CheckEvents(out Event e)
+		protected Event GetEvent()
 		{
 			var enetEv = new ENetEvent();
 			int ret = NativeMethods.enet_host_check_events(this.host, enetEv);
-			e = new Event(enetEv);
-			return ret;
+			if (ret <= 0)
+			{
+				return null;
+			}
+			var e = new Event(enetEv);
+			return e;
 		}
 
 		protected int Service(int timeout)
@@ -82,9 +86,9 @@ namespace ENet
 			NativeMethods.enet_host_broadcast(this.host, channelID, packet.PacketPtr);
 		}
 
-		public void CompressWithRangeEncoder()
+		protected void CompressWithRangeCoder()
 		{
-			NativeMethods.enet_host_compress_with_range_encoder(this.host);
+			NativeMethods.enet_host_compress_with_range_coder(this.host);
 		}
 
 		public void DoNotCompress()

+ 3 - 2
CSharp/Platform/ENet/Library.cs

@@ -5,10 +5,11 @@
 		public static void Initialize()
 		{
 			var inits = new ENetCallbacks();
-			int ret = NativeMethods.enet_initialize_with_callbacks(NativeMethods.ENET_VERSION, ref inits);
+			int ret = NativeMethods.enet_initialize_with_callbacks(
+				NativeMethods.ENET_VERSION, ref inits);
 			if (ret < 0)
 			{
-				throw new ENetException(ret, "Initialization failed.");
+				throw new ENetException(string.Format("Initialization failed, ret: {0}", ret));
 			}
 		}
 

+ 3 - 3
CSharp/Platform/ENet/NativeMethods.cs

@@ -42,9 +42,6 @@ namespace ENet
 		[DllImport(LIB, CallingConvention = CallingConvention.Cdecl)]
 		internal static extern void enet_enable_crc(IntPtr host);
 
-		[DllImport(LIB, CallingConvention = CallingConvention.Cdecl)]
-		internal static extern int enet_host_compress_with_range_encoder(IntPtr host);
-
 		[DllImport(LIB, CallingConvention = CallingConvention.Cdecl)]
 		internal static extern IntPtr enet_host_create(
 			ref ENetAddress address, uint peerLimit, uint channelLimit, uint incomingBandwidth,
@@ -68,6 +65,9 @@ namespace ENet
 		[DllImport(LIB, CallingConvention = CallingConvention.Cdecl)]
 		internal static extern void enet_host_compress(IntPtr host, IntPtr compressor);
 
+		[DllImport(LIB, CallingConvention = CallingConvention.Cdecl)]
+		internal static extern int enet_host_compress_with_range_coder(IntPtr host);
+
 		[DllImport(LIB, CallingConvention = CallingConvention.Cdecl)]
 		internal static extern void enet_host_channel_limit(IntPtr host, uint channelLimit);
 

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

@@ -21,7 +21,7 @@ namespace ENet
 			this.packet = NativeMethods.enet_packet_create(data, (uint) data.Length, flags);
 			if (this.packet == IntPtr.Zero)
 			{
-				throw new ENetException(0, "Packet creation call failed.");
+				throw new ENetException("Packet creation call failed");
 			}
 		}
 

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

@@ -102,7 +102,7 @@ namespace ENet
 			{
 				if (e.EventState == EventState.DISCONNECTED)
 				{
-					tcs.TrySetException(new ENetException(3, "Peer Disconnected In Received"));
+					tcs.TrySetException(new ENetException("Peer Disconnected In Received"));
 				}
 				var packet = new Packet(e.PacketPtr);
 				tcs.TrySetResult(packet);

+ 16 - 8
CSharp/Platform/ENet/ServerHost.cs

@@ -5,12 +5,10 @@ namespace ENet
 {
 	public sealed class ServerHost: Host
 	{
-		private Action<Peer> acceptEvent;
-
 		public ServerHost(string hostName, ushort port, 
 			uint peerLimit = NativeMethods.ENET_PROTOCOL_MAXIMUM_PEER_ID,
 			uint channelLimit = 0, uint incomingBandwidth = 0, uint outgoingBandwidth = 0,
-			bool enableCrc = true)
+			bool enableCrc = true, bool compressWithRangeEncoder = true)
 		{
 			if (peerLimit > NativeMethods.ENET_PROTOCOL_MAXIMUM_PEER_ID)
 			{
@@ -26,12 +24,17 @@ namespace ENet
 
 			if (this.host == IntPtr.Zero)
 			{
-				throw new ENetException(0, "Host creation call failed.");
+				throw new ENetException("Host creation call failed.");
 			}
 
 			if (enableCrc)
 			{
-				NativeMethods.enet_enable_crc(this.host);
+				this.EnableCrc();
+			}
+
+			if (compressWithRangeEncoder)
+			{
+				this.CompressWithRangeCoder();
 			}
 		}
 
@@ -39,7 +42,7 @@ namespace ENet
 		{
 			if (this.PeersManager.ContainsKey(IntPtr.Zero))
 			{
-				throw new ENetException(5, "Do Not Accept Twice!");
+				throw new ENetException("Do Not Accept Twice!");
 			}
 			var tcs = new TaskCompletionSource<Peer>();
 			var peer = new Peer(IntPtr.Zero);
@@ -57,9 +60,14 @@ namespace ENet
 				return;
 			}
 
-			Event ev;
-			while (this.CheckEvents(out ev) > 0)
+			while (true)
 			{
+				Event ev = this.GetEvent();
+				if (ev == null)
+				{
+					return;
+				}
+
 				switch (ev.Type)
 				{
 					case EventType.Connect:

+ 1 - 1
CSharp/Platform/ENetTest/ENetClientServerTest.cs

@@ -29,7 +29,7 @@ namespace ENetCSTest
 		}
 
 		private static async void ServerEvent(ServerHost host, Barrier barrier)
-		{
+		{
 			barrier.SignalAndWait();
 			var peer = await host.AcceptAsync();
 			// Client断开,Server端收到Disconnect事件,结束Server线程