Просмотр исходного кода

客户端服务端TCP UDP协议联调都通过了

tanghai 9 лет назад
Родитель
Сommit
68427368f1

+ 1 - 1
Server/App/Program.cs

@@ -28,7 +28,7 @@ namespace App
 				Game.Scene.AddComponent<TimerComponent>();
 				Game.Scene.AddComponent<NetworkComponent, NetworkProtocol, string, int>(options.Protocol, options.Host, options.Port);
 				Game.Scene.AddComponent<MessageHandlerComponent, string>(options.AppType);
-
+				
 				// 根据不同的AppType添加不同的组件
 				switch (options.AppType)
 				{

+ 22 - 5
Server/Base/Log.cs

@@ -1,27 +1,44 @@
-namespace Base
+using System;
+using System.Collections.Generic;
+
+namespace Base
 {
 	public static class Log
 	{
 		private static readonly ILog globalLog = new NLogAdapter(new StackInfoDecorater());
 
+		public static Dictionary<long, Action<LogType, string>> Callback { get; } = new Dictionary<long, Action<LogType, string>>();
+
+		private static void OnCallback(LogType type, string message)
+		{
+			foreach (var action in Callback.Values)
+			{
+				action(type, message);
+			}
+		}
+
 		public static void Warning(string message)
 		{
 			globalLog.Warning(message);
+			OnCallback(LogType.Warning, message);
 		}
 
 		public static void Info(string message)
 		{
 			globalLog.Info(message);
+			OnCallback(LogType.Info, message);
 		}
 
-		public static void Debug(string format)
+		public static void Debug(string message)
 		{
-			globalLog.Debug(format);
+			globalLog.Debug(message);
+			OnCallback(LogType.Debug, message);
 		}
 
-		public static void Error(string format)
+		public static void Error(string message)
 		{
-			globalLog.Error(format);
+			globalLog.Error(message);
+			OnCallback(LogType.Error, message);
 		}
 	}
 }

+ 3 - 0
Server/Base/Server.Base.csproj

@@ -119,6 +119,9 @@
     <Compile Include="..\..\Unity\Assets\Plugins\Base\Helper\ZipHelper.cs">
       <Link>Helper\ZipHelper.cs</Link>
     </Compile>
+    <Compile Include="..\..\Unity\Assets\Plugins\Base\LogType.cs">
+      <Link>LogType.cs</Link>
+    </Compile>
     <Compile Include="..\..\Unity\Assets\Plugins\Base\Message\AMEvent.cs">
       <Link>Message\AMEvent.cs</Link>
     </Compile>

+ 1 - 1
Server/Controller/C2S_LoginEvent.cs

@@ -6,7 +6,7 @@ namespace Controller
 	[Message(AppType.Realm)]
 	public class C2S_LoginEvent: AMEvent<C2S_Login>
 	{
-		public override void Run(Entity scene, C2S_Login message, uint rpcId)
+		protected override void Run(Entity scene, C2S_Login message, uint rpcId)
 		{
 			Log.Info(MongoHelper.ToJson(message));
 			scene.GetComponent<MessageComponent>().Send(rpcId, new S2C_Login {ErrorMessage = new ErrorMessage() });

+ 18 - 0
Server/Controller/C2S_SubscribeLogEvent.cs

@@ -0,0 +1,18 @@
+using Base;
+using Model;
+
+namespace Controller
+{
+	[Message(AppType.Realm)]
+	public class C2S_SubscribeLogEvent : AMEvent<C2S_SubscribeLog>
+	{
+		protected override void Run(Entity entity, C2S_SubscribeLog message, uint rpcId)
+		{
+			Log.Info(MongoHelper.ToJson(message));
+
+			//entity.AddComponent<LogToClientComponent>();
+
+			entity.GetComponent<MessageComponent>().Send(rpcId, new S2C_SubscribeLog { ErrorMessage = new ErrorMessage() });
+		}
+	}
+}

+ 1 - 0
Server/Controller/Server.Controller.csproj

@@ -34,6 +34,7 @@
     <Reference Include="System.Core" />
   </ItemGroup>
   <ItemGroup>
+    <Compile Include="C2S_SubscribeLogEvent.cs" />
     <Compile Include="Properties\AssemblyInfo.cs" />
     <Compile Include="C2S_LoginEvent.cs" />
   </ItemGroup>

+ 43 - 0
Server/Model/Component/LogToClientComponent.cs

@@ -0,0 +1,43 @@
+using Base;
+
+namespace Model
+{
+	[ObjectEvent]
+	public class LogToClientComponentEvent : ObjectEvent<LogToClientComponent>, IAwake
+	{
+		public void Awake()
+		{
+			this.GetValue().Awake();
+		}
+	}
+
+	public class LogToClientComponent : Component
+	{
+		public void Awake()
+		{
+			Log.Callback.Add(this.Id, this.LogToClient);
+		}
+
+		private void LogToClient(LogType type, string message)
+		{
+			if (this.Owner.Id == 0)
+			{
+				return;
+			}
+			this.GetComponent<MessageComponent>().Send(new S2C_ServerLog { Type = type, Log = message });
+		}
+
+		public override void Dispose()
+		{
+			if (this.Id == 0)
+			{
+				return;
+			}
+			long id = this.Id;
+
+			base.Dispose();
+
+			Log.Callback.Remove(id);
+		}
+	}
+}

+ 1 - 0
Server/Model/Server.Model.csproj

@@ -74,6 +74,7 @@
     <Compile Include="..\..\Unity\Assets\Scripts\Other\Options.cs">
       <Link>Other\Options.cs</Link>
     </Compile>
+    <Compile Include="Component\LogToClientComponent.cs" />
     <Compile Include="Component\OptionsComponent.cs" />
     <Compile Include="Properties\AssemblyInfo.cs" />
   </ItemGroup>

+ 27 - 7
Unity/Assets/Editor/ServerCommandLineEditor/UI/ServerCommandLineEditor.cs

@@ -10,6 +10,11 @@ namespace MyEditor
 	public class ServerCommandLineEditor : EditorWindow
 	{
 		private const string Path = @"..\Server\Bin\Debug\CommandLineConfig.txt";
+
+		private int copyNum = 1;
+
+		private NetworkProtocol protocol;
+
 		private CommandLines commandLines;
 
 		[MenuItem("Tools/服务端命令行配置")]
@@ -39,8 +44,10 @@ namespace MyEditor
 				commandLine.IP = EditorGUILayout.TextField(commandLine.IP);
 				GUILayout.Label($"AppType:");
 				commandLine.Options.AppType = EditorGUILayout.TextField(commandLine.Options.AppType);
-				GUILayout.Label($"Name:");
-				commandLine.Options.Name = EditorGUILayout.TextField(commandLine.Options.Name);
+				GUILayout.Label($"Id:");
+				commandLine.Options.Id = EditorGUILayout.IntField(commandLine.Options.Id);
+				GUILayout.Label($"Protocol:");
+				commandLine.Options.Protocol = (NetworkProtocol)EditorGUILayout.EnumPopup(commandLine.Options.Protocol);
 				GUILayout.Label($"Host:");
 				commandLine.Options.Host = EditorGUILayout.TextField(commandLine.Options.Host);
 				GUILayout.Label($"Port:");
@@ -52,18 +59,30 @@ namespace MyEditor
 				}
 				if (GUILayout.Button("复制"))
 				{
-					CommandLine newCommandLine = (CommandLine)commandLine.Clone();
-					this.commandLines.Commands.Add(newCommandLine);
+					for (int j = 1; j < this.copyNum + 1; ++j)
+					{
+						CommandLine newCommandLine = (CommandLine) commandLine.Clone();
+						newCommandLine.Options.Id += j;
+						newCommandLine.Options.Port += j;
+						newCommandLine.Options.Protocol = this.protocol;
+						this.commandLines.Commands.Add(newCommandLine);
+					}
 					break;
 				}
 				GUILayout.EndHorizontal();
 			}
 
+			GUILayout.BeginHorizontal();
+			this.copyNum = EditorGUILayout.IntField("复制数量: ", this.copyNum);
+			this.protocol = (NetworkProtocol)EditorGUILayout.EnumPopup("协议: ", this.protocol);
+			GUILayout.EndHorizontal();
 
+			GUILayout.BeginHorizontal();
 			if (GUILayout.Button("添加"))
 			{
-				CommandLine commandLine = new CommandLine();
-				this.commandLines.Commands.Add(commandLine);
+				CommandLine newCommandLine = new CommandLine();
+				newCommandLine.Options.Protocol = this.protocol;
+				this.commandLines.Commands.Add(newCommandLine);
 			}
 
 			if (GUILayout.Button("保存"))
@@ -75,7 +94,7 @@ namespace MyEditor
 			{
 				foreach (CommandLine commandLine in this.commandLines.Commands)
 				{
-					string arguments = $"--appType={commandLine.Options.AppType} --name={commandLine.Options.Name} --Host={commandLine.Options.Host} --Port={commandLine.Options.Port}";
+					string arguments = $"--appType={commandLine.Options.AppType} --id={commandLine.Options.Id} --Protocol={commandLine.Options.Protocol} --Host={commandLine.Options.Host} --Port={commandLine.Options.Port}";
 
 					ProcessStartInfo info = new ProcessStartInfo(@"App.exe", arguments)
 					{
@@ -85,6 +104,7 @@ namespace MyEditor
 					Process.Start(info);
 				}
 			}
+			GUILayout.EndHorizontal();
 		}
 
 		void OnDisable()

+ 10 - 0
Unity/Assets/Plugins/Base/LogType.cs

@@ -0,0 +1,10 @@
+namespace Base
+{
+	public enum LogType
+	{
+		Warning,
+		Info,
+		Debug,
+		Error,
+	}
+}

+ 12 - 0
Unity/Assets/Plugins/Base/LogType.cs.meta

@@ -0,0 +1,12 @@
+fileFormatVersion: 2
+guid: 8fa6ec6493510da42a2448ae9baf909b
+timeCreated: 1476689599
+licenseType: Pro
+MonoImporter:
+  serializedVersion: 2
+  defaultReferences: []
+  executionOrder: 0
+  icon: {instanceID: 0}
+  userData: 
+  assetBundleName: 
+  assetBundleVariant: 

+ 1 - 1
Unity/Assets/Plugins/Base/Message/AMEvent.cs

@@ -2,7 +2,7 @@
 {
 	public abstract class AMEvent<T>: IMRegister
 	{
-		public abstract void Run(Entity scene, T message, uint rpcId);
+		protected abstract void Run(Entity scene, T message, uint rpcId);
 
 		public void Register(IMessageHandler component)
 		{

+ 2 - 3
Unity/Assets/Plugins/Base/Network/TNet/PacketParser.cs

@@ -23,11 +23,11 @@ namespace Base
 			this.buffer = buffer;
 		}
 
-		private bool Parse()
+		private void Parse()
 		{
 			if (this.isOK)
 			{
-				return true;
+				return;
 			}
 
 			bool finish = false;
@@ -67,7 +67,6 @@ namespace Base
 						break;
 				}
 			}
-			return this.isOK;
 		}
 
 		public byte[] GetPacket()

+ 14 - 6
Unity/Assets/Plugins/Base/Network/TNet/TChannel.cs

@@ -44,6 +44,7 @@ namespace Base
 			this.socket = socket;
 			this.parser = new PacketParser(this.recvBuffer);
 			this.RemoteAddress = socket.RemoteAddress;
+			this.OnAccepted();
 		}
 
 		public override void Dispose()
@@ -60,7 +61,14 @@ namespace Base
 			this.socket.Dispose();
 			this.service.Remove(id);
 		}
-		
+
+		private void OnAccepted()
+		{
+			this.isConnected = true;
+			this.StartSend();
+			this.StartRecv();
+		}
+
 		private void OnConnected(long channelId, SocketError error)
 		{
 			if (this.service.GetChannel(channelId) == null)
@@ -137,7 +145,6 @@ namespace Base
 			this.socket.OnSend = null;
 			if (error != SocketError.Success)
 			{
-				Log.Info($"socket send fail, error: {error}, n: {n}");
 				this.OnError(this, error);
 				return;
 			}
@@ -154,6 +161,7 @@ namespace Base
 		private void StartRecv()
 		{
 			int size = TBuffer.ChunkSize - this.recvBuffer.LastIndex;
+			
 			if (!this.socket.RecvAsync(this.recvBuffer.Last, this.recvBuffer.LastIndex, size))
 			{
 				this.OnRecv(size, SocketError.Success);
@@ -170,25 +178,25 @@ namespace Base
 			this.socket.OnRecv = null;
 			if (error != SocketError.Success)
 			{
-				Log.Info($"socket recv fail, error: {error}, {n}");
 				this.OnError(this, error);
 				return;
 			}
-
+			
 			this.recvBuffer.LastIndex += n;
 			if (this.recvBuffer.LastIndex == TBuffer.ChunkSize)
 			{
 				this.recvBuffer.AddLast();
 				this.recvBuffer.LastIndex = 0;
 			}
-
+			
 			if (this.recvTcs != null)
 			{
 				byte[] packet = this.parser.GetPacket();
 				if (packet != null)
 				{
-					this.recvTcs.SetResult(packet);
+					var tcs = this.recvTcs;
 					this.recvTcs = null;
+					tcs.SetResult(packet);
 				}
 			}
 

+ 0 - 1
Unity/Assets/Scripts/Component/MessageComponent.cs

@@ -155,7 +155,6 @@ namespace Model
 		public Task<Response> CallAsync<Response>(object request) where Response : IErrorMessage
 		{
 			this.Send(++RpcId, request);
-
 			var tcs = new TaskCompletionSource<Response>();
 			this.requestCallback[RpcId] = (bytes, offset, count) =>
 			{

+ 5 - 0
Unity/Assets/Scripts/Init.cs

@@ -25,6 +25,11 @@ namespace Model
 		{
 			Base.Object.ObjectManager.Update();
 		}
+
+		private void OnApplicationQuit()
+		{
+			Game.Close();
+		}
 	}
 }
 

+ 21 - 0
Unity/Assets/Scripts/Message/Message.cs

@@ -20,4 +20,25 @@ namespace Model
 		public string Host;
 		public int Port;
 	}
+
+	[Opcode(3)]
+	[BsonIgnoreExtraElements]
+	public class S2C_ServerLog
+	{
+		public LogType Type;
+		public string Log;
+	}
+
+	[Opcode(4)]
+	[BsonIgnoreExtraElements]
+	public class C2S_SubscribeLog
+	{
+	}
+
+	[Opcode(5)]
+	[BsonIgnoreExtraElements]
+	public class S2C_SubscribeLog: IErrorMessage
+	{
+		public ErrorMessage ErrorMessage { get; set; }
+	}
 }

+ 2 - 2
Unity/Assets/Scripts/Other/Options.cs

@@ -14,9 +14,9 @@ namespace Model
 		public string AppType { get; set; }
 
 #if SERVER
-		[Option("name", Required = true, HelpText = "Name.")]
+		[Option("id", Required = true, HelpText = "Id.")]
 #endif
-		public string Name { get; set; }
+		public int Id { get; set; }
 
 #if SERVER
 		[Option("protocol", Required = false, HelpText = "Protocol, tcp or udp.", DefaultValue = NetworkProtocol.UDP)]

+ 3 - 1
Unity/Controller/Event/InitSceneStartEvent_InitGame.cs

@@ -13,11 +13,13 @@ namespace Controller
 		public async void Run()
 		{
 			Game.Scene.AddComponent<MessageHandlerComponent, string>("Client");
-			NetworkComponent networkComponent = Game.Scene.AddComponent<NetworkComponent, NetworkProtocol>(NetworkProtocol.UDP);
+			NetworkComponent networkComponent = Game.Scene.AddComponent<NetworkComponent, NetworkProtocol>(NetworkProtocol.TCP);
 			Entity session = networkComponent.Get("127.0.0.1:8888");
 
 			try
 			{
+				// 订阅服务端日志, 服务端收到这个消息会将之后的日志转发给客户端
+				await session.GetComponent<MessageComponent>().CallAsync<S2C_SubscribeLog>(new C2S_SubscribeLog());
 				S2C_Login s2CLogin = await session.GetComponent<MessageComponent>().CallAsync<S2C_Login>(new C2S_Login {Account = "tanghai", Password = "1111111"});
 				Log.Info(MongoHelper.ToJson(s2CLogin));
 			}

+ 13 - 0
Unity/Controller/Message/S2C_ServerLogEvent.cs

@@ -0,0 +1,13 @@
+using Base;
+using Model;
+
+namespace Controller
+{
+	public class S2C_ServerLogEvent: AMEvent<S2C_ServerLog>
+	{
+		protected override void Run(Entity scene, S2C_ServerLog message, uint rpcId)
+		{
+			Log.Debug(message.Log);
+		}
+	}
+}

+ 1 - 1
Unity/Controller/Unity.Controller.csproj

@@ -54,6 +54,7 @@
   </ItemGroup>
   <ItemGroup>
     <Compile Include="Event\InitSceneStartEvent_InitGame.cs" />
+    <Compile Include="Message\S2C_ServerLogEvent.cs" />
     <Compile Include="Properties\AssemblyInfo.cs" />
   </ItemGroup>
   <ItemGroup>
@@ -70,7 +71,6 @@
     <Folder Include="Factory\" />
     <Folder Include="Helper\" />
     <Folder Include="Logic\" />
-    <Folder Include="Message\" />
   </ItemGroup>
   <Import Project="$(MSBuildToolsPath)\Microsoft.CSharp.targets" />
   <PropertyGroup>

+ 1 - 0
Unity/Unity.CSharp.Plugins.csproj

@@ -98,6 +98,7 @@
     <Compile Include="Assets\Plugins\Base\Helper\TimeHelper.cs" />
     <Compile Include="Assets\Plugins\Base\Helper\ZipHelper.cs" />
     <Compile Include="Assets\Plugins\Base\Log.cs" />
+    <Compile Include="Assets\Plugins\Base\LogType.cs" />
     <Compile Include="Assets\Plugins\Base\Message\AMEvent.cs" />
     <Compile Include="Assets\Plugins\Base\Message\IErrorMessage.cs" />
     <Compile Include="Assets\Plugins\Base\Message\IMRegister.cs" />