MessageComponent.cs 11 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440
  1. using System;
  2. using System.Collections.Generic;
  3. using System.Linq;
  4. using System.Reflection;
  5. using System.Threading;
  6. using System.Threading.Tasks;
  7. namespace Base
  8. {
  9. public enum NetChannelType
  10. {
  11. Login,
  12. Gate,
  13. Battle,
  14. }
  15. [ObjectEvent]
  16. public class MessageComponentEvent : ObjectEvent<MessageComponent>, ILoader, IAwake, IUpdate
  17. {
  18. public void Load()
  19. {
  20. this.GetValue().Load();
  21. }
  22. public void Awake()
  23. {
  24. this.GetValue().Awake();
  25. }
  26. public void Update()
  27. {
  28. this.GetValue().Update();
  29. }
  30. }
  31. /// <summary>
  32. /// 消息分发组件
  33. /// </summary>
  34. public class MessageComponent: Component
  35. {
  36. private uint RpcId { get; set; }
  37. private Dictionary<Opcode, List<Action<byte[], int, int>>> events;
  38. private readonly Dictionary<uint, Action<byte[], int, int>> requestCallback = new Dictionary<uint, Action<byte[], int, int>>();
  39. private readonly Dictionary<Opcode, Action<byte[], int, int>> waitCallback = new Dictionary<Opcode, Action<byte[], int, int>>();
  40. private readonly Dictionary<NetChannelType, AChannel> channels = new Dictionary<NetChannelType, AChannel>();
  41. public void Awake()
  42. {
  43. this.Load();
  44. }
  45. public void Load()
  46. {
  47. this.events = new Dictionary<Opcode, List<Action<byte[], int, int>>>();
  48. Assembly[] assemblies = Object.ObjectManager.GetAssemblies();
  49. foreach (Assembly assembly in assemblies)
  50. {
  51. Type[] types = assembly.GetTypes();
  52. foreach (Type type in types)
  53. {
  54. object[] attrs = type.GetCustomAttributes(typeof(MessageAttribute), false);
  55. if (attrs.Length == 0)
  56. {
  57. continue;
  58. }
  59. MessageAttribute messageAttribute = (MessageAttribute)attrs[0];
  60. if (messageAttribute.SceneType != this.GetComponent<Scene>().SceneType)
  61. {
  62. continue;
  63. }
  64. object obj = Activator.CreateInstance(type);
  65. IMRegister<MessageComponent> iMRegister = obj as IMRegister<MessageComponent>;
  66. if (iMRegister == null)
  67. {
  68. throw new GameException($"message handler not inherit IEventSync or IEventAsync interface: {obj.GetType().FullName}");
  69. }
  70. iMRegister.Register(this);
  71. }
  72. }
  73. }
  74. public void Register<T>(Action<Unit, T> action)
  75. {
  76. Opcode opcode = EnumHelper.FromString<Opcode>(typeof (T).Name);
  77. if (!this.events.ContainsKey(opcode))
  78. {
  79. this.events.Add(opcode, new List<Action<byte[], int, int>>());
  80. }
  81. List<Action<byte[], int, int>> actions = this.events[opcode];
  82. actions.Add((messageBytes, offset, count) =>
  83. {
  84. T t;
  85. try
  86. {
  87. t = MongoHelper.FromBson<T>(messageBytes, offset, count);
  88. }
  89. catch (Exception ex)
  90. {
  91. throw new GameException("解释消息失败:" + opcode, ex);
  92. }
  93. if (OpcodeHelper.IsNeedDebugLogMessage(opcode))
  94. {
  95. Log.Debug(MongoHelper.ToJson(t));
  96. }
  97. action(this.Owner, t);
  98. });
  99. }
  100. public void Connect(NetChannelType channelType, string host, int port)
  101. {
  102. AChannel channel = Share.Scene.GetComponent<NetworkComponent>().ConnectChannel(host, port);
  103. this.channels[channelType] = channel;
  104. }
  105. public void Close(NetChannelType channelType)
  106. {
  107. AChannel channel = this.GetChannel(channelType);
  108. if (channel == null || channel.Id == 0)
  109. {
  110. return;
  111. }
  112. this.channels.Remove(channelType);
  113. channel.Dispose();
  114. }
  115. public void Update()
  116. {
  117. foreach (AChannel channel in this.channels.Values.ToArray())
  118. {
  119. this.UpdateChannel(channel);
  120. }
  121. }
  122. private void UpdateChannel(AChannel channel)
  123. {
  124. if (channel.Id == 0)
  125. {
  126. return;
  127. }
  128. while (true)
  129. {
  130. byte[] messageBytes = channel.Recv();
  131. if (messageBytes == null)
  132. {
  133. return;
  134. }
  135. if (messageBytes.Length < 6)
  136. {
  137. continue;
  138. }
  139. Opcode opcode = (Opcode)BitConverter.ToUInt16(messageBytes, 0);
  140. try
  141. {
  142. this.Run(opcode, messageBytes);
  143. }
  144. catch (Exception e)
  145. {
  146. Log.Error(e.ToString());
  147. }
  148. }
  149. }
  150. public void Run(Opcode opcode, byte[] messageBytes)
  151. {
  152. int offset = 0;
  153. uint flagUInt = BitConverter.ToUInt32(messageBytes, 2);
  154. bool isCompressed = (byte)(flagUInt >> 24) == 1;
  155. if (isCompressed) // 表示有压缩,需要解压缩
  156. {
  157. messageBytes = ZipHelper.Decompress(messageBytes, 6, messageBytes.Length - 6);
  158. offset = 0;
  159. }
  160. else
  161. {
  162. offset = 6;
  163. }
  164. uint rpcId = flagUInt & 0x0fff;
  165. this.RunDecompressedBytes(opcode, rpcId, messageBytes, offset);
  166. }
  167. public void RunDecompressedBytes(Opcode opcode, uint rpcId, byte[] messageBytes, int offset)
  168. {
  169. Action<byte[], int, int> action;
  170. if (this.requestCallback.TryGetValue(rpcId, out action))
  171. {
  172. this.requestCallback.Remove(rpcId);
  173. action(messageBytes, offset, messageBytes.Length - offset);
  174. return;
  175. }
  176. if (this.waitCallback.TryGetValue(opcode, out action))
  177. {
  178. this.waitCallback.Remove(opcode);
  179. action(messageBytes, offset, messageBytes.Length - offset);
  180. return;
  181. }
  182. List<Action<byte[], int, int>> actions;
  183. if (!this.events.TryGetValue(opcode, out actions))
  184. {
  185. if (this.GetComponent<Scene>().SceneType == SceneType.Game)
  186. {
  187. Log.Error($"消息{opcode}没有处理");
  188. }
  189. return;
  190. }
  191. foreach (var ev in actions)
  192. {
  193. try
  194. {
  195. ev(messageBytes, offset, messageBytes.Length - offset);
  196. }
  197. catch (Exception e)
  198. {
  199. Log.Error(e.ToString());
  200. }
  201. }
  202. }
  203. public Task<Response> CallAsync<Response>(object request, CancellationToken cancellationToken) where Response : IErrorMessage
  204. {
  205. this.Send(request, ++this.RpcId);
  206. var tcs = new TaskCompletionSource<Response>();
  207. this.requestCallback[this.RpcId] = (bytes, offset, count) =>
  208. {
  209. try
  210. {
  211. Response response = MongoHelper.FromBson<Response>(bytes, offset, count);
  212. Opcode opcode = EnumHelper.FromString<Opcode>(response.GetType().Name);
  213. if (OpcodeHelper.IsNeedDebugLogMessage(opcode))
  214. {
  215. Log.Debug(MongoHelper.ToJson(response));
  216. }
  217. if (response.ErrorMessage.errno != (int)ErrorCode.ERR_Success)
  218. {
  219. tcs.SetException(new RpcException((ErrorCode)response.ErrorMessage.errno, response.ErrorMessage.msg.Utf8ToStr()));
  220. return;
  221. }
  222. tcs.SetResult(response);
  223. }
  224. catch (Exception e)
  225. {
  226. tcs.SetException(new GameException($"Rpc Error: {typeof(Response).FullName}", e));
  227. }
  228. };
  229. cancellationToken.Register(() => { this.requestCallback.Remove(this.RpcId); });
  230. return tcs.Task;
  231. }
  232. /// <summary>
  233. /// Rpc调用,发送一个消息,等待返回一个消息
  234. /// </summary>
  235. /// <typeparam name="Response"></typeparam>
  236. /// <param name="request"></param>
  237. /// <returns></returns>
  238. public Task<Response> CallAsync<Response>(object request) where Response : IErrorMessage
  239. {
  240. this.Send(request, ++this.RpcId);
  241. var tcs = new TaskCompletionSource<Response>();
  242. this.requestCallback[this.RpcId] = (bytes, offset, count) =>
  243. {
  244. try
  245. {
  246. Response response = MongoHelper.FromBson<Response>(bytes, offset, count);
  247. Opcode opcode = EnumHelper.FromString<Opcode>(response.GetType().Name);
  248. if (OpcodeHelper.IsNeedDebugLogMessage(opcode))
  249. {
  250. Log.Debug(MongoHelper.ToJson(response));
  251. }
  252. if (response.ErrorMessage.errno != (int) ErrorCode.ERR_Success)
  253. {
  254. tcs.SetException(new RpcException((ErrorCode)response.ErrorMessage.errno, response.ErrorMessage.msg.Utf8ToStr()));
  255. return;
  256. }
  257. tcs.SetResult(response);
  258. }
  259. catch (Exception e)
  260. {
  261. tcs.SetException(new GameException($"Rpc Error: {typeof(Response).FullName}", e));
  262. }
  263. };
  264. return tcs.Task;
  265. }
  266. /// <summary>
  267. /// 不发送消息,直接等待返回一个消息
  268. /// </summary>
  269. /// <typeparam name="Response"></typeparam>
  270. /// <param name="cancellationToken"></param>
  271. /// <returns></returns>
  272. public Task<Response> WaitAsync<Response>(CancellationToken cancellationToken) where Response : class
  273. {
  274. var tcs = new TaskCompletionSource<Response>();
  275. Opcode opcode = EnumHelper.FromString<Opcode>(typeof(Response).Name);
  276. this.waitCallback[opcode] = (bytes, offset, count) =>
  277. {
  278. try
  279. {
  280. Response response = MongoHelper.FromBson<Response>(bytes, offset, count);
  281. Opcode op = EnumHelper.FromString<Opcode>(response.GetType().Name);
  282. if (OpcodeHelper.IsNeedDebugLogMessage(op))
  283. {
  284. Log.Debug(MongoHelper.ToJson(response));
  285. }
  286. tcs.SetResult(response);
  287. }
  288. catch (Exception e)
  289. {
  290. tcs.SetException(new GameException($"Wait Error: {typeof(Response).FullName}", e));
  291. }
  292. };
  293. cancellationToken.Register(() => { this.waitCallback.Remove(opcode); });
  294. return tcs.Task;
  295. }
  296. /// <summary>
  297. /// 不发送消息,直接等待返回一个消息
  298. /// </summary>
  299. /// <typeparam name="Response"></typeparam>
  300. /// <returns></returns>
  301. public Task<Response> WaitAsync<Response>() where Response : class
  302. {
  303. var tcs = new TaskCompletionSource<Response>();
  304. Opcode opcode = EnumHelper.FromString<Opcode>(typeof(Response).Name);
  305. this.waitCallback[opcode] = (bytes, offset, count) =>
  306. {
  307. try
  308. {
  309. Response response = MongoHelper.FromBson<Response>(bytes, offset, count);
  310. Opcode op = EnumHelper.FromString<Opcode>(response.GetType().Name);
  311. if (OpcodeHelper.IsNeedDebugLogMessage(op))
  312. {
  313. Log.Debug(MongoHelper.ToJson(response));
  314. }
  315. tcs.SetResult(response);
  316. }
  317. catch (Exception e)
  318. {
  319. tcs.SetException(new GameException($"Wait Error: {typeof(Response).FullName}", e));
  320. }
  321. };
  322. return tcs.Task;
  323. }
  324. public AChannel GetChannel(NetChannelType channelType)
  325. {
  326. AChannel channel;
  327. this.channels.TryGetValue(channelType, out channel);
  328. return channel;
  329. }
  330. public void Send(object message)
  331. {
  332. this.Send(message, 0);
  333. }
  334. public bool IsChannelConnected(NetChannelType channelType)
  335. {
  336. AChannel channel = GetChannel(channelType);
  337. if (channel == null)
  338. {
  339. return false;
  340. }
  341. return true;
  342. }
  343. private void Send(object message, uint rpcId)
  344. {
  345. Opcode opcode = EnumHelper.FromString<Opcode>(message.GetType().Name);
  346. byte[] opcodeBytes = BitConverter.GetBytes((ushort)opcode);
  347. byte[] seqBytes = BitConverter.GetBytes(rpcId);
  348. byte[] messageBytes = MongoHelper.ToBson(message);
  349. NetChannelType channelType;
  350. if ((ushort)opcode > 7000 && (ushort)opcode < 8000)
  351. {
  352. channelType = NetChannelType.Login;
  353. }
  354. else if ((ushort)opcode > 0 && (ushort)opcode <= 1000)
  355. {
  356. channelType = NetChannelType.Battle;
  357. }
  358. else
  359. {
  360. channelType = NetChannelType.Gate;
  361. }
  362. AChannel channel = this.GetChannel(channelType);
  363. if (channel == null)
  364. {
  365. throw new GameException("game channel not found!");
  366. }
  367. channel.Send(new List<byte[]> { opcodeBytes, seqBytes, messageBytes });
  368. if (OpcodeHelper.IsNeedDebugLogMessage(opcode))
  369. {
  370. Log.Debug(MongoHelper.ToJson(message));
  371. }
  372. }
  373. public override void Dispose()
  374. {
  375. if (this.Id == 0)
  376. {
  377. return;
  378. }
  379. base.Dispose();
  380. foreach (AChannel channel in this.channels.Values.ToArray())
  381. {
  382. channel.Dispose();
  383. }
  384. }
  385. }
  386. }