Răsfoiți Sursa

抽出了基础库,接下来可以把服务端代码和客户端代码合并

tanghai 9 ani în urmă
părinte
comite
748d7e7155
100 a modificat fișierele cu 758 adăugiri și 148 ștergeri
  1. 0 0
      Unity/Assets/Plugins/Base.meta
  2. 9 0
      Unity/Assets/Plugins/Base/Component.meta
  3. 19 17
      Unity/Assets/Plugins/Base/Component/EventComponent.cs
  4. 2 2
      Unity/Assets/Plugins/Base/Component/EventComponent.cs.meta
  5. 2 2
      Unity/Assets/Plugins/Base/Component/KVComponent.cs
  6. 2 2
      Unity/Assets/Plugins/Base/Component/KVComponent.cs.meta
  7. 3 2
      Unity/Assets/Plugins/Base/Component/LogComponent.cs
  8. 2 2
      Unity/Assets/Plugins/Base/Component/LogComponent.cs.meta
  9. 254 0
      Unity/Assets/Plugins/Base/Component/MessageComponent.cs
  10. 2 2
      Unity/Assets/Plugins/Base/Component/MessageComponent.cs.meta
  11. 131 0
      Unity/Assets/Plugins/Base/Component/MessageHandlerComponent.cs
  12. 12 0
      Unity/Assets/Plugins/Base/Component/MessageHandlerComponent.cs.meta
  13. 4 4
      Unity/Assets/Plugins/Base/Component/NetworkComponent.cs
  14. 2 2
      Unity/Assets/Plugins/Base/Component/NetworkComponent.cs.meta
  15. 3 1
      Unity/Assets/Plugins/Base/Component/TimeComponent.cs
  16. 2 2
      Unity/Assets/Plugins/Base/Component/TimeComponent.cs.meta
  17. 2 1
      Unity/Assets/Plugins/Base/Component/TimerComponent.cs
  18. 2 2
      Unity/Assets/Plugins/Base/Component/TimerComponent.cs.meta
  19. 0 0
      Unity/Assets/Plugins/Base/Config.meta
  20. 8 8
      Unity/Assets/Plugins/Base/Config/ACategory.cs
  21. 0 0
      Unity/Assets/Plugins/Base/Config/ACategory.cs.meta
  22. 0 0
      Unity/Assets/Plugins/Base/Config/AConfig.cs
  23. 0 0
      Unity/Assets/Plugins/Base/Config/AConfig.cs.meta
  24. 0 0
      Unity/Assets/Plugins/Base/Config/ConfigAttribute.cs
  25. 0 0
      Unity/Assets/Plugins/Base/Config/ConfigAttribute.cs.meta
  26. 0 0
      Unity/Assets/Plugins/Base/Config/ICategory.cs
  27. 0 0
      Unity/Assets/Plugins/Base/Config/ICategory.cs.meta
  28. 0 0
      Unity/Assets/Plugins/Base/DoubleMap.cs
  29. 0 0
      Unity/Assets/Plugins/Base/DoubleMap.cs.meta
  30. 9 0
      Unity/Assets/Plugins/Base/Event.meta
  31. 4 3
      Unity/Assets/Plugins/Base/Event/AEventAttribute.cs
  32. 2 2
      Unity/Assets/Plugins/Base/Event/AEventAttribute.cs.meta
  33. 4 2
      Unity/Assets/Plugins/Base/Event/Env.cs
  34. 2 2
      Unity/Assets/Plugins/Base/Event/Env.cs.meta
  35. 10 0
      Unity/Assets/Plugins/Base/Event/EnvBaseKey.cs
  36. 12 0
      Unity/Assets/Plugins/Base/Event/EnvBaseKey.cs.meta
  37. 9 0
      Unity/Assets/Plugins/Base/Event/EventAttribute.cs
  38. 2 2
      Unity/Assets/Plugins/Base/Event/EventAttribute.cs.meta
  39. 9 0
      Unity/Assets/Plugins/Base/Event/EventBaseType.cs
  40. 12 0
      Unity/Assets/Plugins/Base/Event/EventBaseType.cs.meta
  41. 1 1
      Unity/Assets/Plugins/Base/Event/IEvent.cs
  42. 2 2
      Unity/Assets/Plugins/Base/Event/IEvent.cs.meta
  43. 3 2
      Unity/Assets/Plugins/Base/Game.cs
  44. 2 2
      Unity/Assets/Plugins/Base/Game.cs.meta
  45. 0 0
      Unity/Assets/Plugins/Base/Helper.meta
  46. 0 0
      Unity/Assets/Plugins/Base/Helper/ArrayHelper.cs
  47. 0 0
      Unity/Assets/Plugins/Base/Helper/ArrayHelper.cs.meta
  48. 0 0
      Unity/Assets/Plugins/Base/Helper/ByteHelper.cs
  49. 0 0
      Unity/Assets/Plugins/Base/Helper/ByteHelper.cs.meta
  50. 0 0
      Unity/Assets/Plugins/Base/Helper/EnumHelper.cs
  51. 0 0
      Unity/Assets/Plugins/Base/Helper/EnumHelper.cs.meta
  52. 0 0
      Unity/Assets/Plugins/Base/Helper/FileHelper.cs
  53. 0 0
      Unity/Assets/Plugins/Base/Helper/FileHelper.cs.meta
  54. 0 0
      Unity/Assets/Plugins/Base/Helper/IdGenerater.cs
  55. 0 0
      Unity/Assets/Plugins/Base/Helper/IdGenerater.cs.meta
  56. 0 0
      Unity/Assets/Plugins/Base/Helper/MD5Helper.cs
  57. 0 0
      Unity/Assets/Plugins/Base/Helper/MD5Helper.cs.meta
  58. 0 0
      Unity/Assets/Plugins/Base/Helper/MongoHelper.cs
  59. 0 0
      Unity/Assets/Plugins/Base/Helper/MongoHelper.cs.meta
  60. 0 0
      Unity/Assets/Plugins/Base/Helper/ProtobufHelper.cs
  61. 0 0
      Unity/Assets/Plugins/Base/Helper/ProtobufHelper.cs.meta
  62. 0 0
      Unity/Assets/Plugins/Base/Helper/RandomHelper.cs
  63. 0 0
      Unity/Assets/Plugins/Base/Helper/RandomHelper.cs.meta
  64. 0 0
      Unity/Assets/Plugins/Base/Helper/StringHelper.cs
  65. 0 0
      Unity/Assets/Plugins/Base/Helper/StringHelper.cs.meta
  66. 1 7
      Unity/Assets/Plugins/Base/Helper/TimeHelper.cs
  67. 0 0
      Unity/Assets/Plugins/Base/Helper/TimeHelper.cs.meta
  68. 0 0
      Unity/Assets/Plugins/Base/Helper/ZipHelper.cs
  69. 0 0
      Unity/Assets/Plugins/Base/Helper/ZipHelper.cs.meta
  70. 0 5
      Unity/Assets/Plugins/Base/Log.cs
  71. 1 1
      Unity/Assets/Plugins/Base/Log.cs.meta
  72. 9 0
      Unity/Assets/Plugins/Base/Message.meta
  73. 15 0
      Unity/Assets/Plugins/Base/Message/AMEvent.cs
  74. 2 2
      Unity/Assets/Plugins/Base/Message/AMEvent.cs.meta
  75. 2 1
      Unity/Assets/Plugins/Base/Message/IErrorMessage.cs
  76. 2 2
      Unity/Assets/Plugins/Base/Message/IErrorMessage.cs.meta
  77. 7 0
      Unity/Assets/Plugins/Base/Message/IMRegister.cs
  78. 2 2
      Unity/Assets/Plugins/Base/Message/IMRegister.cs.meta
  79. 14 4
      Unity/Assets/Plugins/Base/Message/MessageAttribute.cs
  80. 2 2
      Unity/Assets/Plugins/Base/Message/MessageAttribute.cs.meta
  81. 23 0
      Unity/Assets/Plugins/Base/Message/RpcException.cs
  82. 12 0
      Unity/Assets/Plugins/Base/Message/RpcException.cs.meta
  83. 0 0
      Unity/Assets/Plugins/Base/MultiMap.cs
  84. 0 0
      Unity/Assets/Plugins/Base/MultiMap.cs.meta
  85. 0 0
      Unity/Assets/Plugins/Base/Network.meta
  86. 3 4
      Unity/Assets/Plugins/Base/Network/AChannel.cs
  87. 0 0
      Unity/Assets/Plugins/Base/Network/AChannel.cs.meta
  88. 7 2
      Unity/Assets/Plugins/Base/Network/AService.cs
  89. 0 0
      Unity/Assets/Plugins/Base/Network/AService.cs.meta
  90. 0 0
      Unity/Assets/Plugins/Base/Network/TNet.meta
  91. 7 2
      Unity/Assets/Plugins/Base/Network/TNet/PacketParser.cs
  92. 0 0
      Unity/Assets/Plugins/Base/Network/TNet/PacketParser.cs.meta
  93. 1 1
      Unity/Assets/Plugins/Base/Network/TNet/TBuffer.cs
  94. 0 0
      Unity/Assets/Plugins/Base/Network/TNet/TBuffer.cs.meta
  95. 53 25
      Unity/Assets/Plugins/Base/Network/TNet/TChannel.cs
  96. 0 0
      Unity/Assets/Plugins/Base/Network/TNet/TChannel.cs.meta
  97. 0 0
      Unity/Assets/Plugins/Base/Network/TNet/TPoller.cs
  98. 0 0
      Unity/Assets/Plugins/Base/Network/TNet/TPoller.cs.meta
  99. 51 21
      Unity/Assets/Plugins/Base/Network/TNet/TService.cs
  100. 0 0
      Unity/Assets/Plugins/Base/Network/TNet/TService.cs.meta

+ 0 - 0
Unity/Assets/Scripts/Base.meta → Unity/Assets/Plugins/Base.meta


+ 9 - 0
Unity/Assets/Plugins/Base/Component.meta

@@ -0,0 +1,9 @@
+fileFormatVersion: 2
+guid: d558fe8e3a6cad64c82e41a65bb3826f
+folderAsset: yes
+timeCreated: 1476427109
+licenseType: Pro
+DefaultImporter:
+  userData: 
+  assetBundleName: 
+  assetBundleVariant: 

+ 19 - 17
Unity/Assets/Scripts/Component/Scene/EventComponent.cs → Unity/Assets/Plugins/Base/Component/EventComponent.cs

@@ -1,8 +1,10 @@
 using System;
 using System.Collections.Generic;
 using System.Reflection;
+using Base;
+using Object = Base.Object;
 
-namespace Base
+namespace Model
 {
 	[ObjectEvent]
 	public class EventComponentEvent : ObjectEvent<EventComponent>, ILoader, IAwake
@@ -23,11 +25,11 @@ namespace Base
 	/// </summary>
 	public class EventComponent: Component
 	{
-		private Dictionary<EventIdType, List<object>> allEvents;
+		private Dictionary<int, List<object>> allEvents;
 
 		public void Load()
 		{
-			this.allEvents = new Dictionary<EventIdType, List<object>>();
+			this.allEvents = new Dictionary<int, List<object>>();
 			Assembly[] assemblies = Object.ObjectManager.GetAssemblies();
 			foreach (Assembly assembly in assemblies)
 			{
@@ -51,7 +53,7 @@ namespace Base
 			}
 		}
 
-		public void Run(EventIdType type)
+		public void Run(int type)
 		{
 			List<object> iEvents = null;
 			if (!this.allEvents.TryGetValue(type, out iEvents))
@@ -66,7 +68,7 @@ namespace Base
 					IEvent iEvent = obj as IEvent;
 					if (iEvent == null)
 					{
-						throw new GameException($"event type: {type} is not IEvent");
+						throw new Exception($"event type: {type} is not IEvent");
 					}
 					iEvent.Run();
 				}
@@ -77,7 +79,7 @@ namespace Base
 			}
 		}
 
-		public void Run<A>(EventIdType type, A a)
+		public void Run<A>(int type, A a)
 		{
 			List<object> iEvents = null;
 			if (!this.allEvents.TryGetValue(type, out iEvents))
@@ -92,7 +94,7 @@ namespace Base
 					var iEvent = obj as IEvent<A>;
 					if (iEvent == null)
 					{
-						throw new GameException($"event type: {type} is not IEvent<{typeof (A).Name}>");
+						throw new Exception($"event type: {type} is not IEvent<{typeof (A).Name}>");
 					}
 					iEvent.Run(a);
 				}
@@ -103,7 +105,7 @@ namespace Base
 			}
 		}
 
-		public void Run<A, B>(EventIdType type, A a, B b)
+		public void Run<A, B>(int type, A a, B b)
 		{
 			List<object> iEvents = null;
 			if (!this.allEvents.TryGetValue(type, out iEvents))
@@ -118,7 +120,7 @@ namespace Base
 					var iEvent = obj as IEvent<A, B>;
 					if (iEvent == null)
 					{
-						throw new GameException($"event type: {type} is not IEvent<{typeof (A).Name}, {typeof (B).Name}>");
+						throw new Exception($"event type: {type} is not IEvent<{typeof (A).Name}, {typeof (B).Name}>");
 					}
 					iEvent.Run(a, b);
 				}
@@ -129,7 +131,7 @@ namespace Base
 			}
 		}
 
-		public void Run<A, B, C>(EventIdType type, A a, B b, C c)
+		public void Run<A, B, C>(int type, A a, B b, C c)
 		{
 			List<object> iEvents = null;
 			if (!this.allEvents.TryGetValue(type, out iEvents))
@@ -144,7 +146,7 @@ namespace Base
 					var iEvent = obj as IEvent<A, B, C>;
 					if (iEvent == null)
 					{
-						throw new GameException($"event type: {type} is not IEvent<{typeof (A).Name}, {typeof (B).Name}, {typeof (C).Name}>");
+						throw new Exception($"event type: {type} is not IEvent<{typeof (A).Name}, {typeof (B).Name}, {typeof (C).Name}>");
 					}
 					iEvent.Run(a, b, c);
 				}
@@ -155,7 +157,7 @@ namespace Base
 			}
 		}
 
-		public void Run<A, B, C, D>(EventIdType type, A a, B b, C c, D d)
+		public void Run<A, B, C, D>(int type, A a, B b, C c, D d)
 		{
 			List<object> iEvents = null;
 			if (!this.allEvents.TryGetValue(type, out iEvents))
@@ -170,7 +172,7 @@ namespace Base
 					var iEvent = obj as IEvent<A, B, C, D>;
 					if (iEvent == null)
 					{
-						throw new GameException($"event type: {type} is not IEvent<{typeof (A).Name}, {typeof (B).Name}, {typeof (C).Name}, {typeof (D).Name}>");
+						throw new Exception($"event type: {type} is not IEvent<{typeof (A).Name}, {typeof (B).Name}, {typeof (C).Name}, {typeof (D).Name}>");
 					}
 					iEvent.Run(a, b, c, d);
 				}
@@ -181,7 +183,7 @@ namespace Base
 			}
 		}
 
-		public void Run<A, B, C, D, E>(EventIdType type, A a, B b, C c, D d, E e)
+		public void Run<A, B, C, D, E>(int type, A a, B b, C c, D d, E e)
 		{
 			List<object> iEvents = null;
 			if (!this.allEvents.TryGetValue(type, out iEvents))
@@ -196,7 +198,7 @@ namespace Base
 					var iEvent = obj as IEvent<A, B, C, D, E>;
 					if (iEvent == null)
 					{
-						throw new GameException(
+						throw new Exception(
 								$"event type: {type} is not IEvent<{typeof (A).Name}, {typeof (B).Name}, {typeof (C).Name}, {typeof (D).Name}, {typeof (E).Name}>");
 					}
 					iEvent.Run(a, b, c, d, e);
@@ -207,7 +209,7 @@ namespace Base
 				}
 			}
 		}
-        public void Run<A, B, C, D, E,F>(EventIdType type, A a, B b, C c, D d, E e,F f)
+        public void Run<A, B, C, D, E,F>(int type, A a, B b, C c, D d, E e,F f)
         {
             List<object> iEvents = null;
             if (!this.allEvents.TryGetValue(type, out iEvents))
@@ -222,7 +224,7 @@ namespace Base
                     var iEvent = obj as IEvent<A, B, C, D, E,F>;
                     if (iEvent == null)
                     {
-                        throw new GameException(
+                        throw new Exception(
                                 $"event type: {type} is not IEvent<{typeof(A).Name}, {typeof(B).Name}, {typeof(C).Name}, {typeof(D).Name}, {typeof(E).Name}>");
                     }
                     iEvent.Run(a, b, c, d, e,f);

+ 2 - 2
Unity/Assets/Scripts/Component/Scene/EventComponent.cs.meta → Unity/Assets/Plugins/Base/Component/EventComponent.cs.meta

@@ -1,6 +1,6 @@
 fileFormatVersion: 2
-guid: dab907cc827e2a94db68f5b057471b48
-timeCreated: 1474944344
+guid: cfb3b30793a2f664487948e085514abe
+timeCreated: 1476427109
 licenseType: Pro
 MonoImporter:
   serializedVersion: 2

+ 2 - 2
Unity/Assets/Scripts/Component/KVComponent.cs → Unity/Assets/Plugins/Base/Component/KVComponent.cs

@@ -1,8 +1,8 @@
 using System.Collections.Generic;
-using System.Linq;
+using Base;
 using MongoDB.Bson.Serialization.Attributes;
 
-namespace Base
+namespace Model
 {
 	/// <summary>
 	/// Key Value组件用于保存一些数据

+ 2 - 2
Unity/Assets/Scripts/Component/KVComponent.cs.meta → Unity/Assets/Plugins/Base/Component/KVComponent.cs.meta

@@ -1,6 +1,6 @@
 fileFormatVersion: 2
-guid: 17265c1c4bf06a94da594ce31869e163
-timeCreated: 1475893345
+guid: e72548f682c0f584f82c92748e6bc7ec
+timeCreated: 1476427964
 licenseType: Pro
 MonoImporter:
   serializedVersion: 2

+ 3 - 2
Unity/Assets/Scripts/Component/Scene/LogComponent.cs → Unity/Assets/Plugins/Base/Component/LogComponent.cs

@@ -1,8 +1,9 @@
 using System;
 using System.IO;
 using System.Text;
+using Base;
 
-namespace Base
+namespace Model
 {
 	[ObjectEvent]
 	public class LogComponentEvent : ObjectEvent<LogComponent>, IAwake
@@ -92,7 +93,7 @@ namespace Base
 			if (timeNow - SendToServerTime > SendToServerFrequency)
 			{
 				SendToServerTime = timeNow;
-				Share.Scene.GetComponent<EventComponent>().Run(EventIdType.LogError, s);
+				Game.Scene.GetComponent<EventComponent>().Run(EventBaseType.LogError, s);
 			}
 		}
 

+ 2 - 2
Unity/Assets/Scripts/Component/Scene/LogComponent.cs.meta → Unity/Assets/Plugins/Base/Component/LogComponent.cs.meta

@@ -1,6 +1,6 @@
 fileFormatVersion: 2
-guid: 100ba9b6c7922cd4b98b67b4bc193d1e
-timeCreated: 1474944344
+guid: 1551ca8574c888743a5b3e614de8123f
+timeCreated: 1476427963
 licenseType: Pro
 MonoImporter:
   serializedVersion: 2

+ 254 - 0
Unity/Assets/Plugins/Base/Component/MessageComponent.cs

@@ -0,0 +1,254 @@
+using System;
+using System.Collections.Generic;
+using System.Threading;
+using System.Threading.Tasks;
+using Base;
+
+namespace Model
+{
+	[ObjectEvent]
+	public class MessageComponentEvent : ObjectEvent<MessageComponent>, IAwake<MessageHandlerComponent, AChannel>
+	{
+		public void Awake(MessageHandlerComponent messageHandler, AChannel aChannel)
+		{
+			this.GetValue().Awake(messageHandler, aChannel);
+		}
+	}
+	
+	/// <summary>
+	/// 消息收发
+	/// </summary>
+	public class MessageComponent: Component
+	{
+		private uint RpcId { get; set; }
+		private readonly Dictionary<uint, Action<byte[], int, int>> requestCallback = new Dictionary<uint, Action<byte[], int, int>>();
+		private readonly Dictionary<ushort, Action<byte[], int, int>> waitCallback = new Dictionary<ushort, Action<byte[], int, int>>();
+		private AChannel channel;
+		private MessageHandlerComponent messageHandler;
+		
+		public void Awake(MessageHandlerComponent handler, AChannel aChannel)
+		{
+			this.messageHandler = handler;
+			this.channel = aChannel;
+			this.UpdateChannel();
+		}
+		
+		private async void UpdateChannel()
+		{
+			while (true)
+			{
+				byte[] messageBytes;
+				try
+				{
+					messageBytes = await channel.Recv();
+				}
+				catch (Exception e)
+				{
+					Log.Error(e.ToString());
+					continue;
+				}
+
+				if (messageBytes.Length < 6)
+				{
+					continue;
+				}
+
+				ushort opcode = BitConverter.ToUInt16(messageBytes, 0);
+				try
+				{
+					this.Run(opcode, messageBytes);
+				}
+				catch (Exception e)
+				{
+					Log.Error(e.ToString());
+				}
+			}
+		}
+
+		private void Run(ushort opcode, byte[] messageBytes)
+		{
+			int offset = 0;
+			uint flagUInt = BitConverter.ToUInt32(messageBytes, 2);
+			bool isCompressed = (byte)(flagUInt >> 24) == 1;
+			if (isCompressed) // 表示有压缩,需要解压缩
+			{
+				messageBytes = ZipHelper.Decompress(messageBytes, 6, messageBytes.Length - 6);
+				offset = 0;
+			}
+			else
+			{
+				offset = 6;
+			}
+			uint rpcId = flagUInt & 0x0fff;
+			this.RunDecompressedBytes(opcode, rpcId, messageBytes, offset);
+		}
+
+		private void RunDecompressedBytes(ushort opcode, uint rpcId, byte[] messageBytes, int offset)
+		{
+			Action<byte[], int, int> action;
+			if (this.requestCallback.TryGetValue(rpcId, out action))
+			{
+				this.requestCallback.Remove(rpcId);
+				action(messageBytes, offset, messageBytes.Length - offset);
+				return;
+			}
+
+			if (this.waitCallback.TryGetValue(opcode, out action))
+			{
+				this.waitCallback.Remove(opcode);
+				action(messageBytes, offset, messageBytes.Length - offset);
+				return;
+			}
+
+			this.messageHandler.Handle(this.Owner, opcode, messageBytes, offset);
+		}
+
+
+		public Task<Response> CallAsync<Response>(object request, CancellationToken cancellationToken) where Response : IErrorMessage
+		{
+			this.Send(request, ++this.RpcId);
+
+			var tcs = new TaskCompletionSource<Response>();
+
+			this.requestCallback[this.RpcId] = (bytes, offset, count) =>
+			{
+				try
+				{
+					Response response = MongoHelper.FromBson<Response>(bytes, offset, count);
+					ushort opcode = this.messageHandler.MessageOpcode[request.GetType()];
+					if (response.ErrorMessage.errno != 0)
+					{
+						tcs.SetException(new RpcException(response.ErrorMessage.errno, response.ErrorMessage.msg.Utf8ToStr()));
+						return;
+					}
+					tcs.SetResult(response);
+				}
+				catch (Exception e)
+				{
+					tcs.SetException(new Exception($"Rpc Error: {typeof(Response).FullName}", e));
+				}
+			};
+
+			cancellationToken.Register(() => { this.requestCallback.Remove(this.RpcId); });
+
+			return tcs.Task;
+		}
+
+		/// <summary>
+		/// Rpc调用,发送一个消息,等待返回一个消息
+		/// </summary>
+		/// <typeparam name="Response"></typeparam>
+		/// <param name="request"></param>
+		/// <returns></returns>
+		public Task<Response> CallAsync<Response>(object request) where Response : IErrorMessage
+		{
+			this.Send(request, ++this.RpcId);
+
+			var tcs = new TaskCompletionSource<Response>();
+			this.requestCallback[this.RpcId] = (bytes, offset, count) =>
+			{
+				try
+				{
+					Response response = MongoHelper.FromBson<Response>(bytes, offset, count);
+					if (response.ErrorMessage.errno != 0)
+					{
+						tcs.SetException(new RpcException(response.ErrorMessage.errno,  response.ErrorMessage.msg.Utf8ToStr()));
+						return;
+					}
+					tcs.SetResult(response);
+				}
+				catch (Exception e)
+				{
+					tcs.SetException(new Exception($"Rpc Error: {typeof(Response).FullName}", e));
+				}
+			};
+			
+			return tcs.Task;
+		}
+
+		/// <summary>
+		/// 不发送消息,直接等待返回一个消息
+		/// </summary>
+		/// <typeparam name="Response"></typeparam>
+		/// <param name="cancellationToken"></param>
+		/// <returns></returns>
+		public Task<Response> WaitAsync<Response>(CancellationToken cancellationToken) where Response : class
+		{
+			var tcs = new TaskCompletionSource<Response>();
+			ushort opcode = this.messageHandler.MessageOpcode[typeof(Response)];
+			this.waitCallback[opcode] = (bytes, offset, count) =>
+			{
+				try
+				{
+					Response response = MongoHelper.FromBson<Response>(bytes, offset, count);
+					tcs.SetResult(response);
+				}
+				catch (Exception e)
+				{
+					tcs.SetException(new Exception($"Wait Error: {typeof(Response).FullName}", e));
+				}
+			};
+
+			cancellationToken.Register(() => { this.waitCallback.Remove(opcode); });
+
+			return tcs.Task;
+		}
+
+		/// <summary>
+		/// 不发送消息,直接等待返回一个消息
+		/// </summary>
+		/// <typeparam name="Response"></typeparam>
+		/// <returns></returns>
+		public Task<Response> WaitAsync<Response>() where Response : class
+		{
+			var tcs = new TaskCompletionSource<Response>();
+			ushort opcode = this.messageHandler.MessageOpcode[typeof(Response)];
+			this.waitCallback[opcode] = (bytes, offset, count) =>
+			{
+				try
+				{
+					Response response = MongoHelper.FromBson<Response>(bytes, offset, count);
+					tcs.SetResult(response);
+				}
+				catch (Exception e)
+				{
+					tcs.SetException(new Exception($"Wait Error: {typeof(Response).FullName}", e));
+				}
+			};
+
+			return tcs.Task;
+		}
+
+		public void Send(object message)
+		{
+			this.Send(message, 0);
+		}
+
+		private void Send(object message, uint rpcId)
+		{
+			ushort opcode = this.messageHandler.MessageOpcode[message.GetType()];
+			byte[] opcodeBytes = BitConverter.GetBytes(opcode);
+			byte[] seqBytes = BitConverter.GetBytes(rpcId);
+			byte[] messageBytes = MongoHelper.ToBson(message);
+			
+			if (channel == null)
+			{
+				throw new Exception("game channel not found!");
+			}
+
+			channel.Send(new List<byte[]> { opcodeBytes, seqBytes, messageBytes });
+		}
+
+		public override void Dispose()
+		{
+			if (this.Id == 0)
+			{
+				return;
+			}
+
+			base.Dispose();
+
+			channel.Dispose();
+		}
+	}
+}

+ 2 - 2
Unity/Assets/Scripts/Component/Scene/MessageComponent.cs.meta → Unity/Assets/Plugins/Base/Component/MessageComponent.cs.meta

@@ -1,6 +1,6 @@
 fileFormatVersion: 2
-guid: d04ec0251ae1eb14f87ec0288a7537a1
-timeCreated: 1474948030
+guid: 036da353bafc88746b4c6dc2d3a9c6ae
+timeCreated: 1476427109
 licenseType: Pro
 MonoImporter:
   serializedVersion: 2

+ 131 - 0
Unity/Assets/Plugins/Base/Component/MessageHandlerComponent.cs

@@ -0,0 +1,131 @@
+using System;
+using System.Collections.Generic;
+using System.Reflection;
+using Base;
+using Object = Base.Object;
+
+namespace Model
+{
+	[ObjectEvent]
+	public class MessageHandlerComponentEvent : ObjectEvent<MessageHandlerComponent>, ILoader, IAwake<MessageType>
+	{
+		public void Load()
+		{
+			this.GetValue().Load();
+		}
+
+		public void Awake(MessageType messageType)
+		{
+			this.GetValue().Awake(messageType);
+		}
+	}
+	
+	/// <summary>
+	/// 消息分发组件
+	/// </summary>
+	public class MessageHandlerComponent: Component
+	{
+		private MessageType MessageType;
+		private Dictionary<ushort, List<Action<Entity, byte[], int, int>>> events;
+		public Dictionary<Type, ushort> MessageOpcode { get; private set; } = new Dictionary<Type, ushort>();
+		
+		public void Awake(MessageType messageType)
+		{
+			this.MessageType = messageType;
+			this.Load();
+		}
+
+		public void Load()
+		{
+			this.events = new Dictionary<ushort, List<Action<Entity, byte[], int, int>>>();
+			this.MessageOpcode = new Dictionary<Type, ushort>();
+
+			Assembly[] assemblies = Object.ObjectManager.GetAssemblies();
+			foreach (Assembly assembly in assemblies)
+			{
+				Type[] types = assembly.GetTypes();
+				foreach (Type type in types)
+				{
+					object[] attrs = type.GetCustomAttributes(typeof(MessageAttribute), false);
+					if (attrs.Length == 0)
+					{
+						continue;
+					}
+
+					MessageAttribute messageAttribute = (MessageAttribute)attrs[0];
+					if (messageAttribute.MessageType != this.MessageType)
+					{
+						continue;
+					}
+
+					object obj = Activator.CreateInstance(type);
+
+					IMRegister<MessageHandlerComponent> iMRegister = obj as IMRegister<MessageHandlerComponent>;
+					if (iMRegister == null)
+					{
+						throw new Exception($"message handler not inherit IEventSync or IEventAsync interface: {obj.GetType().FullName}");
+					}
+					iMRegister.Register(this, messageAttribute.Opcode);
+				}
+			}
+		}
+
+		public void Register<T>(ushort opcode, Action<Entity, T> action)
+		{
+			if (!this.events.ContainsKey(opcode))
+			{
+				this.events.Add(opcode, new List<Action<Entity, byte[], int, int>>());
+			}
+			List<Action<Entity, byte[], int, int>> actions = this.events[opcode];
+
+			actions.Add((entity, messageBytes, offset, count) =>
+			{
+				T t;
+				try
+			    {
+                    t = MongoHelper.FromBson<T>(messageBytes, offset, count);
+                }
+			    catch (Exception ex)
+			    {
+			        throw new Exception("解释消息失败:" + opcode, ex);
+			    }
+
+				action(entity, t);
+			});
+		}
+
+
+		public void Handle(Entity entity, ushort opcode, byte[] messageBytes, int offset)
+		{
+			List<Action<Entity, byte[], int, int>> actions;
+			if (!this.events.TryGetValue(opcode, out actions))
+			{
+				Log.Error($"消息{opcode}没有处理");
+				return;
+			}
+
+			foreach (var ev in actions)
+			{
+				try
+				{
+					ev(entity, messageBytes, offset, messageBytes.Length - offset);
+				}
+				catch (Exception e)
+				{
+					Log.Error(e.ToString());
+				}
+			}
+		}
+		
+
+		public override void Dispose()
+		{
+			if (this.Id == 0)
+			{
+				return;
+			}
+
+			base.Dispose();
+		}
+	}
+}

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

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

+ 4 - 4
Unity/Assets/Scripts/Component/Scene/NetworkComponent.cs → Unity/Assets/Plugins/Base/Component/NetworkComponent.cs

@@ -1,7 +1,8 @@
 using System;
 using System.Net.Sockets;
+using Base;
 
-namespace Base
+namespace Model
 {
 	[ObjectEvent]
 	public class NetworkComponentEvent : ObjectEvent<NetworkComponent>, IUpdate, IAwake<NetworkProtocol>
@@ -82,15 +83,14 @@ namespace Base
 		public AChannel ConnectChannel(string host, int port)
 		{
 			AChannel channel = this.service.GetChannel(host, port);
-			channel.ConnectAsync();
 			return channel;
 		}
 
 		public void OnError(long id, SocketError error)
 		{
 			Env env = new Env();
-			env[EnvKey.ChannelError] = error;
-			Share.Scene.GetComponent<EventComponent>().Run(EventIdType.NetworkChannelError, env);
+			env[EnvBaseKey.ChannelError] = error;
+			Game.Scene.GetComponent<EventComponent>().Run(EventBaseType.NetworkChannelError, env);
 		}
 
 		public void RemoveChannel(long channelId)

+ 2 - 2
Unity/Assets/Scripts/Component/Scene/NetworkComponent.cs.meta → Unity/Assets/Plugins/Base/Component/NetworkComponent.cs.meta

@@ -1,6 +1,6 @@
 fileFormatVersion: 2
-guid: 9c37f1d8332d2de4b864376b67572794
-timeCreated: 1474944344
+guid: 18e8dac8edb032f4da7021896febf6b4
+timeCreated: 1476427963
 licenseType: Pro
 MonoImporter:
   serializedVersion: 2

+ 3 - 1
Unity/Assets/Scripts/Component/Scene/TimeComponent.cs → Unity/Assets/Plugins/Base/Component/TimeComponent.cs

@@ -1,4 +1,6 @@
-namespace Base
+using Base;
+
+namespace Model
 {
 	/// <summary>
 	/// 用于同步服务端和客户端时间

+ 2 - 2
Unity/Assets/Scripts/Component/Scene/TimeComponent.cs.meta → Unity/Assets/Plugins/Base/Component/TimeComponent.cs.meta

@@ -1,6 +1,6 @@
 fileFormatVersion: 2
-guid: 2cc9e461ee5efb24c9702e0df1a860b5
-timeCreated: 1474945123
+guid: f149185a7df54774383b4883e3bcc6ef
+timeCreated: 1476427964
 licenseType: Pro
 MonoImporter:
   serializedVersion: 2

+ 2 - 1
Unity/Assets/Scripts/Component/Scene/TimerComponent.cs → Unity/Assets/Plugins/Base/Component/TimerComponent.cs

@@ -1,9 +1,10 @@
 using System.Collections.Generic;
 using System.Threading;
 using System.Threading.Tasks;
+using Base;
 using MongoDB.Bson;
 
-namespace Base
+namespace Model
 {
 	public class Timer
 	{

+ 2 - 2
Unity/Assets/Scripts/Component/Scene/TimerComponent.cs.meta → Unity/Assets/Plugins/Base/Component/TimerComponent.cs.meta

@@ -1,6 +1,6 @@
 fileFormatVersion: 2
-guid: f4d9ff60dc5bc424d8b9e35b76c5a937
-timeCreated: 1474946082
+guid: d5ba602e9f553ff44b1baef3f68a563b
+timeCreated: 1476427964
 licenseType: Pro
 MonoImporter:
   serializedVersion: 2

+ 0 - 0
Unity/Assets/Scripts/Base/Config.meta → Unity/Assets/Plugins/Base/Config.meta


+ 8 - 8
Unity/Assets/Scripts/Base/Config/ACategory.cs → Unity/Assets/Plugins/Base/Config/ACategory.cs

@@ -1,7 +1,7 @@
 using System;
 using System.Collections.Generic;
+using System.IO;
 using System.Linq;
-using UnityEngine;
 
 namespace Base
 {
@@ -9,7 +9,7 @@ namespace Base
 	/// 管理该所有的配置
 	/// </summary>
 	/// <typeparam name="T"></typeparam>
-	public abstract class ACategory<T>: ICategory where T : AConfig
+	public abstract class ACategory<T> : ICategory where T : AConfig
 	{
 		protected Dictionary<long, T> dict;
 
@@ -17,15 +17,15 @@ namespace Base
 		{
 			this.dict = new Dictionary<long, T>();
 
-			string path = $@"Config/{typeof (T).Name}";
+			string path = $@"Config/{typeof(T).Name}";
 			string configStr;
 			try
 			{
-				configStr = ((GameObject)Resources.Load("Config")).Get<TextAsset>(typeof(T).Name).text;
+				configStr = File.ReadAllText(path);
 			}
 			catch (Exception)
 			{
-				throw new GameException($"load config file fail, path: {path}");
+				throw new Exception($"load config file fail, path: {path}");
 			}
 
 			foreach (string str in configStr.Split(new[] { "\r\n" }, StringSplitOptions.None))
@@ -42,7 +42,7 @@ namespace Base
 				}
 				catch (Exception e)
 				{
-					throw new GameException($"parser json fail: {str}", e);
+					throw new Exception($"parser json fail: {str}", e);
 				}
 			}
 		}
@@ -51,7 +51,7 @@ namespace Base
 		{
 			get
 			{
-				return typeof (T);
+				return typeof(T);
 			}
 		}
 
@@ -66,7 +66,7 @@ namespace Base
 				T t;
 				if (!this.dict.TryGetValue(type, out t))
 				{
-					throw new ConfigException($"{typeof (T)} 没有找到配置, key: {type}");
+					throw new Exception($"{typeof(T)} 没有找到配置, key: {type}");
 				}
 				return t;
 			}

+ 0 - 0
Unity/Assets/Scripts/Base/Config/ACategory.cs.meta → Unity/Assets/Plugins/Base/Config/ACategory.cs.meta


+ 0 - 0
Unity/Assets/Scripts/Base/Config/AConfig.cs → Unity/Assets/Plugins/Base/Config/AConfig.cs


+ 0 - 0
Unity/Assets/Scripts/Base/Config/AConfig.cs.meta → Unity/Assets/Plugins/Base/Config/AConfig.cs.meta


+ 0 - 0
Unity/Assets/Scripts/Base/Config/ConfigAttribute.cs → Unity/Assets/Plugins/Base/Config/ConfigAttribute.cs


+ 0 - 0
Unity/Assets/Scripts/Base/Config/ConfigAttribute.cs.meta → Unity/Assets/Plugins/Base/Config/ConfigAttribute.cs.meta


+ 0 - 0
Unity/Assets/Scripts/Base/Config/ICategory.cs → Unity/Assets/Plugins/Base/Config/ICategory.cs


+ 0 - 0
Unity/Assets/Scripts/Base/Config/ICategory.cs.meta → Unity/Assets/Plugins/Base/Config/ICategory.cs.meta


+ 0 - 0
Unity/Assets/Scripts/Base/DoubleMap.cs → Unity/Assets/Plugins/Base/DoubleMap.cs


+ 0 - 0
Unity/Assets/Scripts/Base/DoubleMap.cs.meta → Unity/Assets/Plugins/Base/DoubleMap.cs.meta


+ 9 - 0
Unity/Assets/Plugins/Base/Event.meta

@@ -0,0 +1,9 @@
+fileFormatVersion: 2
+guid: 3bd13b1e460a3684580d79ebf98ab1ee
+folderAsset: yes
+timeCreated: 1476427109
+licenseType: Pro
+DefaultImporter:
+  userData: 
+  assetBundleName: 
+  assetBundleVariant: 

+ 4 - 3
Unity/Assets/Scripts/Other/AEventAttribute.cs → Unity/Assets/Plugins/Base/Event/AEventAttribute.cs

@@ -1,13 +1,14 @@
 using System;
+using Base;
 
-namespace Base
+namespace Model
 {
 	[AttributeUsage(AttributeTargets.Class, AllowMultiple = true)]
 	public abstract class AEventAttribute: Attribute
 	{
-		public EventIdType Type { get; private set; }
+		public int Type { get; private set; }
 
-        protected AEventAttribute(EventIdType type)
+        protected AEventAttribute(int type)
         {
 			this.Type = type;
 		}

+ 2 - 2
Unity/Assets/Scripts/Other/AEventAttribute.cs.meta → Unity/Assets/Plugins/Base/Event/AEventAttribute.cs.meta

@@ -1,6 +1,6 @@
 fileFormatVersion: 2
-guid: b388ceee164d1874395be7e772d005ef
-timeCreated: 1474944934
+guid: 6cb036769594f324aba294b491873809
+timeCreated: 1476427109
 licenseType: Pro
 MonoImporter:
   serializedVersion: 2

+ 4 - 2
Unity/Assets/Scripts/Other/Env.cs → Unity/Assets/Plugins/Base/Event/Env.cs

@@ -1,9 +1,11 @@
 using System;
 using System.Collections;
 using System.Collections.Generic;
+using Base;
 using MongoDB.Bson.Serialization.Attributes;
+using Object = System.Object;
 
-namespace Base
+namespace Model
 {
 	public class Env: Object
 	{
@@ -39,7 +41,7 @@ namespace Base
 			}
 			catch (InvalidCastException e)
 			{
-				throw new GameException($"不能把{value.GetType()}转换为{typeof(T)}", e);
+				throw new Exception($"不能把{value.GetType()}转换为{typeof(T)}", e);
 			}
 		}
 

+ 2 - 2
Unity/Assets/Scripts/Other/Env.cs.meta → Unity/Assets/Plugins/Base/Event/Env.cs.meta

@@ -1,6 +1,6 @@
 fileFormatVersion: 2
-guid: 532badf6e248b90429e30611013d748d
-timeCreated: 1474945035
+guid: 75e0372bd6348034982793f1f89c8638
+timeCreated: 1476427109
 licenseType: Pro
 MonoImporter:
   serializedVersion: 2

+ 10 - 0
Unity/Assets/Plugins/Base/Event/EnvBaseKey.cs

@@ -0,0 +1,10 @@
+namespace Model
+{
+	/// <summary>
+	/// 一般使用事件名+变量名
+	/// </summary>
+	public static class EnvBaseKey
+	{
+		public const string ChannelError = "ChannelError";
+	}
+}

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

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

+ 9 - 0
Unity/Assets/Plugins/Base/Event/EventAttribute.cs

@@ -0,0 +1,9 @@
+namespace Model
+{
+    public class EventAttribute : AEventAttribute
+    {
+        public EventAttribute(int type) : base(type)
+        {
+        }
+    }
+}

+ 2 - 2
Unity/Assets/Scripts/Other/EventAttribute.cs.meta → Unity/Assets/Plugins/Base/Event/EventAttribute.cs.meta

@@ -1,6 +1,6 @@
 fileFormatVersion: 2
-guid: ee52a0f884098594e9dff5c6f61e09e7
-timeCreated: 1474944344
+guid: 6bfe281cef9c246428de3929dad18b42
+timeCreated: 1476427109
 licenseType: Pro
 MonoImporter:
   serializedVersion: 2

+ 9 - 0
Unity/Assets/Plugins/Base/Event/EventBaseType.cs

@@ -0,0 +1,9 @@
+namespace Model
+{
+    public static class EventBaseType
+	{
+		public const int LogError = 1;
+		public const int NetworkChannelError = 2;
+		public const int InitSceneStart = 10;
+    }
+}

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

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

+ 1 - 1
Unity/Assets/Scripts/Other/IEvent.cs → Unity/Assets/Plugins/Base/Event/IEvent.cs

@@ -1,4 +1,4 @@
-namespace Base
+namespace Model
 {
 	public interface IEvent
 	{

+ 2 - 2
Unity/Assets/Scripts/Other/IEvent.cs.meta → Unity/Assets/Plugins/Base/Event/IEvent.cs.meta

@@ -1,6 +1,6 @@
 fileFormatVersion: 2
-guid: 67277ac004a0cde40850709311a1291b
-timeCreated: 1474944999
+guid: 7aede6a4fae88f2438eef33fffe6aeb5
+timeCreated: 1476427109
 licenseType: Pro
 MonoImporter:
   serializedVersion: 2

+ 3 - 2
Unity/Assets/Scripts/Component/Game.cs → Unity/Assets/Plugins/Base/Game.cs

@@ -1,4 +1,6 @@
-namespace Base
+using Base;
+
+namespace Model
 {
 	public sealed class Game
 	{
@@ -11,7 +13,6 @@
 				if (game == null)
 				{
 					game = new Entity();
-					game.AddComponent<Scene>();
 				}
 				return game;
 			}

+ 2 - 2
Unity/Assets/Scripts/Component/Game.cs.meta → Unity/Assets/Plugins/Base/Game.cs.meta

@@ -1,6 +1,6 @@
 fileFormatVersion: 2
-guid: d727ac3cbf77bf6419b35f8f32c72ca0
-timeCreated: 1474942922
+guid: 55f8ee3c9055ec44cb405533e23f8ad7
+timeCreated: 1476427963
 licenseType: Pro
 MonoImporter:
   serializedVersion: 2

+ 0 - 0
Unity/Assets/Scripts/Base/Helper.meta → Unity/Assets/Plugins/Base/Helper.meta


+ 0 - 0
Unity/Assets/Scripts/Base/Helper/ArrayHelper.cs → Unity/Assets/Plugins/Base/Helper/ArrayHelper.cs


+ 0 - 0
Unity/Assets/Scripts/Base/Helper/ArrayHelper.cs.meta → Unity/Assets/Plugins/Base/Helper/ArrayHelper.cs.meta


+ 0 - 0
Unity/Assets/Scripts/Base/Helper/ByteHelper.cs → Unity/Assets/Plugins/Base/Helper/ByteHelper.cs


+ 0 - 0
Unity/Assets/Scripts/Base/Helper/ByteHelper.cs.meta → Unity/Assets/Plugins/Base/Helper/ByteHelper.cs.meta


+ 0 - 0
Unity/Assets/Scripts/Base/Helper/EnumHelper.cs → Unity/Assets/Plugins/Base/Helper/EnumHelper.cs


+ 0 - 0
Unity/Assets/Scripts/Base/Helper/EnumHelper.cs.meta → Unity/Assets/Plugins/Base/Helper/EnumHelper.cs.meta


+ 0 - 0
Unity/Assets/Scripts/Base/Helper/FileHelper.cs → Unity/Assets/Plugins/Base/Helper/FileHelper.cs


+ 0 - 0
Unity/Assets/Scripts/Base/Helper/FileHelper.cs.meta → Unity/Assets/Plugins/Base/Helper/FileHelper.cs.meta


+ 0 - 0
Unity/Assets/Scripts/Base/Helper/IdGenerater.cs → Unity/Assets/Plugins/Base/Helper/IdGenerater.cs


+ 0 - 0
Unity/Assets/Scripts/Base/Helper/IdGenerater.cs.meta → Unity/Assets/Plugins/Base/Helper/IdGenerater.cs.meta


+ 0 - 0
Unity/Assets/Scripts/Base/Helper/MD5Helper.cs → Unity/Assets/Plugins/Base/Helper/MD5Helper.cs


+ 0 - 0
Unity/Assets/Scripts/Base/Helper/MD5Helper.cs.meta → Unity/Assets/Plugins/Base/Helper/MD5Helper.cs.meta


+ 0 - 0
Unity/Assets/Scripts/Base/Helper/MongoHelper.cs → Unity/Assets/Plugins/Base/Helper/MongoHelper.cs


+ 0 - 0
Unity/Assets/Scripts/Base/Helper/MongoHelper.cs.meta → Unity/Assets/Plugins/Base/Helper/MongoHelper.cs.meta


+ 0 - 0
Unity/Assets/Scripts/Base/Helper/ProtobufHelper.cs → Unity/Assets/Plugins/Base/Helper/ProtobufHelper.cs


+ 0 - 0
Unity/Assets/Scripts/Base/Helper/ProtobufHelper.cs.meta → Unity/Assets/Plugins/Base/Helper/ProtobufHelper.cs.meta


+ 0 - 0
Unity/Assets/Scripts/Base/Helper/RandomHelper.cs → Unity/Assets/Plugins/Base/Helper/RandomHelper.cs


+ 0 - 0
Unity/Assets/Scripts/Base/Helper/RandomHelper.cs.meta → Unity/Assets/Plugins/Base/Helper/RandomHelper.cs.meta


+ 0 - 0
Unity/Assets/Scripts/Base/Helper/StringHelper.cs → Unity/Assets/Plugins/Base/Helper/StringHelper.cs


+ 0 - 0
Unity/Assets/Scripts/Base/Helper/StringHelper.cs.meta → Unity/Assets/Plugins/Base/Helper/StringHelper.cs.meta


+ 1 - 7
Unity/Assets/Scripts/Base/Helper/TimeHelper.cs → Unity/Assets/Plugins/Base/Helper/TimeHelper.cs

@@ -25,13 +25,7 @@ namespace Base
 		/// <returns></returns>
 		public static long Now()
 		{
-			TimeComponent gameTimeComponent = Game.Scene?.GetComponent<TimeComponent>();
-			if (gameTimeComponent == null)
-			{
-				return TimeHelper.ClientNow();
-			}
-			long t = gameTimeComponent.Now();
-			return t;
+			return ClientNow();
 		}
     }
 }

+ 0 - 0
Unity/Assets/Scripts/Base/Helper/TimeHelper.cs.meta → Unity/Assets/Plugins/Base/Helper/TimeHelper.cs.meta


+ 0 - 0
Unity/Assets/Scripts/Base/Helper/ZipHelper.cs → Unity/Assets/Plugins/Base/Helper/ZipHelper.cs


+ 0 - 0
Unity/Assets/Scripts/Base/Helper/ZipHelper.cs.meta → Unity/Assets/Plugins/Base/Helper/ZipHelper.cs.meta


+ 0 - 5
Unity/Assets/Scripts/Base/Log.cs → Unity/Assets/Plugins/Base/Log.cs

@@ -4,27 +4,22 @@
 	{
         public static void Warning(string msg)
 		{
-			Share.Scene.GetComponent<LogComponent>().Warning(msg);
 		}
 
 		public static void Info(string msg)
 		{
-			Share.Scene.GetComponent<LogComponent>().Info(msg);
 		}
 
 		public static void Error(string msg)
 		{
-			Share.Scene.GetComponent<LogComponent>().Error(msg);
 		}
 
 		public static void Debug(string msg)
 		{
-			Share.Scene.GetComponent<LogComponent>().Debug(msg);
 		}
 
 		public static void Flush()
 		{
-			Share.Scene.GetComponent<LogComponent>().Flush();
 		}
 	}
 }

+ 1 - 1
Unity/Assets/Scripts/Base/Log.cs.meta → Unity/Assets/Plugins/Base/Log.cs.meta

@@ -1,6 +1,6 @@
 fileFormatVersion: 2
 guid: fc246493a8b0d404ba5453ac0dd404d6
-timeCreated: 1463828881
+timeCreated: 1476420531
 licenseType: Pro
 MonoImporter:
   serializedVersion: 2

+ 9 - 0
Unity/Assets/Plugins/Base/Message.meta

@@ -0,0 +1,9 @@
+fileFormatVersion: 2
+guid: 32549de57e26990479432c71eabaa8dd
+folderAsset: yes
+timeCreated: 1476426533
+licenseType: Pro
+DefaultImporter:
+  userData: 
+  assetBundleName: 
+  assetBundleVariant: 

+ 15 - 0
Unity/Assets/Plugins/Base/Message/AMEvent.cs

@@ -0,0 +1,15 @@
+using Base;
+
+namespace Model
+{
+	public abstract class AMEvent<T>: IMRegister<MessageHandlerComponent>
+	{
+		public void Register(MessageHandlerComponent component, ushort opcode)
+		{
+			component.MessageOpcode[typeof(T)] = opcode;
+			component.Register<T>(opcode, Run);
+		}
+
+		public abstract void Run(Entity scene, T message);
+	}
+}

+ 2 - 2
Unity/Assets/Scripts/Message/AMEvent.cs.meta → Unity/Assets/Plugins/Base/Message/AMEvent.cs.meta

@@ -1,6 +1,6 @@
 fileFormatVersion: 2
-guid: c3810c575b524b248900f9b47e085776
-timeCreated: 1474950053
+guid: 4baf1ce7bcc358548b06835969112d12
+timeCreated: 1476426533
 licenseType: Pro
 MonoImporter:
   serializedVersion: 2

+ 2 - 1
Unity/Assets/Scripts/Message/IErrorMessage.cs → Unity/Assets/Plugins/Base/Message/IErrorMessage.cs

@@ -1,8 +1,9 @@
 using System.ComponentModel;
+using Base;
 using MongoDB.Bson;
 using ProtoBuf;
 
-namespace Base
+namespace Model
 {
 	/// <summary>
 	/// 服务端回的RPC消息需要继承这个接口

+ 2 - 2
Unity/Assets/Scripts/Message/IErrorMessage.cs.meta → Unity/Assets/Plugins/Base/Message/IErrorMessage.cs.meta

@@ -1,6 +1,6 @@
 fileFormatVersion: 2
-guid: d8793e0fa3b9ffd499eae15d5be85f94
-timeCreated: 1474947336
+guid: 5fcce1859acc04a47b65461b59de3c5f
+timeCreated: 1476426533
 licenseType: Pro
 MonoImporter:
   serializedVersion: 2

+ 7 - 0
Unity/Assets/Plugins/Base/Message/IMRegister.cs

@@ -0,0 +1,7 @@
+namespace Model
+{
+	public interface IMRegister<in T>
+	{
+		void Register(T component, ushort opcode);
+	}
+}

+ 2 - 2
Unity/Assets/Scripts/Message/IMRegister.cs.meta → Unity/Assets/Plugins/Base/Message/IMRegister.cs.meta

@@ -1,6 +1,6 @@
 fileFormatVersion: 2
-guid: 7bdc6c8efde9f6941a2fada9a85b4679
-timeCreated: 1474948030
+guid: 590cb3094f089124b83a76718332e939
+timeCreated: 1476426533
 licenseType: Pro
 MonoImporter:
   serializedVersion: 2

+ 14 - 4
Unity/Assets/Scripts/Message/MessageAttribute.cs → Unity/Assets/Plugins/Base/Message/MessageAttribute.cs

@@ -1,20 +1,30 @@
 using System;
 
-namespace Base
+namespace Model
 {
+	public enum MessageType
+	{
+		Client,
+		Realm,
+		Gate,
+	}
+
 	/// <summary>
 	/// 搭配MessageComponent用来分发消息
 	/// </summary>
 	public class MessageAttribute : Attribute
 	{
+		public ushort Opcode { get; private set; }
+
 		/// <summary>
 		/// MessageComponent所有者的SceneType必须相同,这个Message Handle才会注册到MessageComponent里面
 		/// </summary>
-		public SceneType SceneType { get; private set; }
+		public MessageType MessageType { get; private set; }
 
-		public MessageAttribute(SceneType sceneType)
+		public MessageAttribute(MessageType messageType, ushort opcode)
 		{
-			this.SceneType = sceneType;
+			this.MessageType = messageType;
+			this.Opcode = opcode;
 		}
 	}
 }

+ 2 - 2
Unity/Assets/Scripts/Message/MessageAttribute.cs.meta → Unity/Assets/Plugins/Base/Message/MessageAttribute.cs.meta

@@ -1,6 +1,6 @@
 fileFormatVersion: 2
-guid: 5c53c322696c7834ca0b69b848ad6bd5
-timeCreated: 1474942922
+guid: fcf293ee7dda23746a98f4308723280e
+timeCreated: 1476426533
 licenseType: Pro
 MonoImporter:
   serializedVersion: 2

+ 23 - 0
Unity/Assets/Plugins/Base/Message/RpcException.cs

@@ -0,0 +1,23 @@
+using System;
+
+namespace Base
+{
+	/// <summary>
+	/// RPC异常,带ErrorCode
+	/// </summary>
+	[Serializable]
+	public class RpcException : Exception
+	{
+		public int Error { get; private set; }
+
+		public RpcException(int error, string message) : base($"{error} : {message}")
+		{
+			this.Error = error;
+		}
+
+		public RpcException(int error, string message, Exception e) : base($"{error} : {message}", e)
+		{
+			this.Error = error;
+		}
+	}
+}

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

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

+ 0 - 0
Unity/Assets/Scripts/Base/MultiMap.cs → Unity/Assets/Plugins/Base/MultiMap.cs


+ 0 - 0
Unity/Assets/Scripts/Base/MultiMap.cs.meta → Unity/Assets/Plugins/Base/MultiMap.cs.meta


+ 0 - 0
Unity/Assets/Scripts/Base/Network.meta → Unity/Assets/Plugins/Base/Network.meta


+ 3 - 4
Unity/Assets/Scripts/Base/Network/AChannel.cs → Unity/Assets/Plugins/Base/Network/AChannel.cs

@@ -1,5 +1,6 @@
 using System;
 using System.Collections.Generic;
+using System.Threading.Tasks;
 
 namespace Base
 {
@@ -22,9 +23,7 @@ namespace Base
 			this.Id = IdGenerater.GenerateId();
 			this.service = service;
 		}
-
-		public abstract void ConnectAsync();
-
+		
 		/// <summary>
 		/// 发送消息
 		/// </summary>
@@ -35,7 +34,7 @@ namespace Base
 		/// <summary>
 		/// 接收消息
 		/// </summary>
-		public abstract byte[] Recv();
+		public abstract Task<byte[]> Recv();
 
 		public virtual void Dispose()
 		{

+ 0 - 0
Unity/Assets/Scripts/Base/Network/AChannel.cs.meta → Unity/Assets/Plugins/Base/Network/AChannel.cs.meta


+ 7 - 2
Unity/Assets/Scripts/Base/Network/AService.cs → Unity/Assets/Plugins/Base/Network/AService.cs

@@ -1,5 +1,8 @@
 using System;
+using System.Collections.Generic;
+using System.Linq;
 using System.Net.Sockets;
+using System.Threading.Tasks;
 
 namespace Base
 {
@@ -22,14 +25,16 @@ namespace Base
 		public abstract AChannel GetChannel(string host, int port);
 
 		public abstract AChannel GetChannel(string address);
-		
+
+		public abstract Task<AChannel> AcceptChannel();
+
 		public abstract void Remove(long channelId);
 
 		public abstract void Update();
 
 		public Action<long, SocketError> OnError;
 
-		public void OnChannelError(long channelId, SocketError error)
+		protected void OnChannelError(long channelId, SocketError error)
 		{
 			this.OnError?.Invoke(channelId, error);
 			this.Remove(channelId);

+ 0 - 0
Unity/Assets/Scripts/Base/Network/AService.cs.meta → Unity/Assets/Plugins/Base/Network/AService.cs.meta


+ 0 - 0
Unity/Assets/Scripts/Base/Network/TNet.meta → Unity/Assets/Plugins/Base/Network/TNet.meta


+ 7 - 2
Unity/Assets/Scripts/Base/Network/TNet/PacketParser.cs → Unity/Assets/Plugins/Base/Network/TNet/PacketParser.cs

@@ -23,7 +23,7 @@ namespace Base
 			this.buffer = buffer;
 		}
 
-		public bool Parse()
+		private bool Parse()
 		{
 			if (this.isOK)
 			{
@@ -46,7 +46,7 @@ namespace Base
 							this.packetSize = BitConverter.ToUInt32(this.packetSizeBuffer, 0);
 							if (packetSize > 1024 * 1024)
 							{
-								throw new GameException($"packet too large, size: {this.packetSize}");
+								throw new Exception($"packet too large, size: {this.packetSize}");
 							}
 							this.state = ParserState.PacketBody;
 						}
@@ -72,6 +72,11 @@ namespace Base
 
 		public byte[] GetPacket()
 		{
+			this.Parse();
+			if (!this.isOK)
+			{
+				return null;
+			}
 			byte[] result = this.packet;
 			this.isOK = false;
 			return result;

+ 0 - 0
Unity/Assets/Scripts/Base/Network/TNet/PacketParser.cs.meta → Unity/Assets/Plugins/Base/Network/TNet/PacketParser.cs.meta


+ 1 - 1
Unity/Assets/Scripts/Base/Network/TNet/TBuffer.cs → Unity/Assets/Plugins/Base/Network/TNet/TBuffer.cs

@@ -77,7 +77,7 @@ namespace Base
 		{
 			if (this.Count < buffer.Length || buffer.Length == 0)
 			{
-				throw new GameException($"bufferList size < n, bufferList: {this.Count} buffer length: {buffer.Length}");
+				throw new Exception($"bufferList size < n, bufferList: {this.Count} buffer length: {buffer.Length}");
 			}
 			int alreadyCopyCount = 0;
 			while (alreadyCopyCount < buffer.Length)

+ 0 - 0
Unity/Assets/Scripts/Base/Network/TNet/TBuffer.cs.meta → Unity/Assets/Plugins/Base/Network/TNet/TBuffer.cs.meta


+ 53 - 25
Unity/Assets/Scripts/Base/Network/TNet/TChannel.cs → Unity/Assets/Plugins/Base/Network/TNet/TChannel.cs

@@ -2,6 +2,7 @@
 using System.Collections.Generic;
 using System.Linq;
 using System.Net.Sockets;
+using System.Threading.Tasks;
 
 namespace Base
 {
@@ -14,16 +15,39 @@ namespace Base
 
 		private bool isSending;
 		private readonly PacketParser parser;
-		private readonly string remoteAddress;
 		private bool isConnected;
 
 		public Action<long, SocketError> OnError;
 
+		public string RemoteAddress { get; }
+		private TaskCompletionSource<byte[]> recvTcs;
+
+		/// <summary>
+		/// connect
+		/// </summary>
 		public TChannel(TSocket socket, string host, int port, TService service) : base(service)
 		{
 			this.socket = socket;
 			this.parser = new PacketParser(this.recvBuffer);
-			this.remoteAddress = host + ":" + port;
+			this.RemoteAddress = host + ":" + port;
+			
+			bool result = this.socket.ConnectAsync(host, port);
+			if (!result)
+			{
+				this.OnConnected(this.Id, SocketError.Success);
+				return;
+			}
+			this.socket.OnConn += e => OnConnected(this.Id, e);
+		}
+
+		/// <summary>
+		/// accept
+		/// </summary>
+		public TChannel(TSocket socket, TService service) : base(service)
+		{
+			this.socket = socket;
+			this.parser = new PacketParser(this.recvBuffer);
+			this.RemoteAddress = socket.RemoteAddress;
 		}
 
 		public override void Dispose()
@@ -40,20 +64,7 @@ namespace Base
 			this.socket.Dispose();
 			this.service.Remove(id);
 		}
-
-		public override void ConnectAsync()
-		{
-			string[] ss = this.remoteAddress.Split(':');
-			int port = int.Parse(ss[1]);
-			bool result = this.socket.ConnectAsync(ss[0], port);
-			if (!result)
-			{
-				this.OnConnected(this.Id, SocketError.Success);
-				return;
-			}
-			this.socket.OnConn += e => OnConnected(this.Id, e);
-		}
-
+		
 		private void OnConnected(long channelId, SocketError error)
 		{
 			if (this.service.GetChannel(channelId) == null)
@@ -96,15 +107,6 @@ namespace Base
 			}
 		}
 
-		public override byte[] Recv()
-		{
-			if (this.parser.Parse())
-			{
-				return this.parser.GetPacket();
-			}
-			return null;
-		}
-
 		private void StartSend()
 		{
 			// 没有数据需要发送
@@ -183,7 +185,33 @@ namespace Base
 				this.recvBuffer.AddLast();
 				this.recvBuffer.LastIndex = 0;
 			}
+
+			if (this.recvTcs != null)
+			{
+				byte[] packet = this.parser.GetPacket();
+				if (packet != null)
+				{
+					this.recvTcs.SetResult(packet);
+					this.recvTcs = null;
+				}
+			}
+
 			StartRecv();
 		}
+
+		public override Task<byte[]> Recv()
+		{
+			TaskCompletionSource<byte[]> tcs = new TaskCompletionSource<byte[]>();
+			byte[] packet = this.parser.GetPacket();
+			if (packet != null)
+			{
+				tcs.SetResult(packet);
+			}
+			else
+			{
+				recvTcs = tcs;
+			}
+			return tcs.Task;
+		}
 	}
 }

+ 0 - 0
Unity/Assets/Scripts/Base/Network/TNet/TChannel.cs.meta → Unity/Assets/Plugins/Base/Network/TNet/TChannel.cs.meta


+ 0 - 0
Unity/Assets/Scripts/Base/Network/TNet/TPoller.cs → Unity/Assets/Plugins/Base/Network/TNet/TPoller.cs


+ 0 - 0
Unity/Assets/Scripts/Base/Network/TNet/TPoller.cs.meta → Unity/Assets/Plugins/Base/Network/TNet/TPoller.cs.meta


+ 51 - 21
Unity/Assets/Scripts/Base/Network/TNet/TService.cs → Unity/Assets/Plugins/Base/Network/TNet/TService.cs

@@ -1,39 +1,48 @@
 using System;
 using System.Collections.Generic;
 using System.Linq;
+using System.Threading.Tasks;
 
 namespace Base
 {
 	public sealed class TService: AService
 	{
 		private TPoller poller = new TPoller();
-		
+		private readonly TSocket acceptor;
+
 		private readonly Dictionary<long, TChannel> idChannels = new Dictionary<long, TChannel>();
-		
-		private void Dispose(bool disposing)
+		private readonly Dictionary<string, TChannel> addressChannels = new Dictionary<string, TChannel>();
+
+		/// <summary>
+		/// 即可做client也可做server
+		/// </summary>
+		/// <param name="host"></param>
+		/// <param name="port"></param>
+		public TService(string host, int port)
+		{
+			this.acceptor = new TSocket(this.poller, host, port);
+		}
+
+		public TService()
+		{
+		}
+
+		public override void Dispose()
 		{
 			if (this.poller == null)
 			{
 				return;
 			}
 
-			if (disposing)
+			foreach (long id in this.idChannels.Keys.ToArray())
 			{
-				foreach (long id in this.idChannels.Keys.ToArray())
-				{
-					TChannel channel = this.idChannels[id];
-					channel.Dispose();
-				}
+				TChannel channel = this.idChannels[id];
+				channel.Dispose();
 			}
 
 			this.poller = null;
 		}
 
-		public override void Dispose()
-		{
-			this.Dispose(true);
-		}
-
 		public override void Add(Action action)
 		{
 			this.poller.Add(action);
@@ -46,6 +55,20 @@ namespace Base
 			return channel;
 		}
 
+		public override async Task<AChannel> AcceptChannel()
+		{
+			if (this.acceptor == null)
+			{
+				throw new Exception("service construct must use host and port param");
+			}
+			TSocket socket = new TSocket(this.poller);
+			await this.acceptor.AcceptAsync(socket);
+			TChannel channel = new TChannel(socket, this);
+			this.addressChannels[channel.RemoteAddress] = channel;
+			this.idChannels[channel.Id] = channel;
+			return channel;
+		}
+
 		public override void Remove(long id)
 		{
 			TChannel channel;
@@ -63,19 +86,26 @@ namespace Base
 
 		public override AChannel GetChannel(string host, int port)
 		{
-			TChannel channel = null;
-			TSocket newSocket = new TSocket(this.poller);
-			channel = new TChannel(newSocket, host, port, this);
-			channel.OnError += this.OnChannelError;
-			this.idChannels[channel.Id] = channel;
-			return channel;
+			string address = $"{host}:{port}";
+			return this.GetChannel(address);
 		}
 
 		public override AChannel GetChannel(string address)
 		{
+			TChannel channel = null;
+			if (this.addressChannels.TryGetValue(address, out channel))
+			{
+				return channel;
+			}
+
 			string[] ss = address.Split(':');
+			string host = ss[0];
 			int port = int.Parse(ss[1]);
-			return this.GetChannel(ss[0], port);
+			TSocket newSocket = new TSocket(this.poller);
+			channel = new TChannel(newSocket, host, port, this);
+			channel.OnError += this.OnChannelError;
+			this.idChannels[channel.Id] = channel;
+			return channel;
 		}
 
 		public override void Update()

+ 0 - 0
Unity/Assets/Scripts/Base/Network/TNet/TService.cs.meta → Unity/Assets/Plugins/Base/Network/TNet/TService.cs.meta


Unele fișiere nu au fost afișate deoarece prea multe fișiere au fost modificate în acest diff