MessageComponent.cs 7.3 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284
  1. using System;
  2. using System.Collections.Generic;
  3. using System.Threading;
  4. using System.Threading.Tasks;
  5. namespace Base
  6. {
  7. public enum NetChannelType
  8. {
  9. Login,
  10. Gate,
  11. Battle,
  12. }
  13. [ObjectEvent]
  14. public class MessageComponentEvent : ObjectEvent<MessageComponent>, IAwake<AChannel>
  15. {
  16. public void Awake(AChannel aChannel)
  17. {
  18. this.GetValue().Awake(aChannel);
  19. }
  20. }
  21. /// <summary>
  22. /// 消息收发
  23. /// </summary>
  24. public class MessageComponent: Component
  25. {
  26. private uint RpcId { get; set; }
  27. private readonly Dictionary<uint, Action<byte[], int, int>> requestCallback = new Dictionary<uint, Action<byte[], int, int>>();
  28. private readonly Dictionary<Opcode, Action<byte[], int, int>> waitCallback = new Dictionary<Opcode, Action<byte[], int, int>>();
  29. private AChannel channel;
  30. public void Awake(AChannel aChannel)
  31. {
  32. this.channel = aChannel;
  33. this.UpdateChannel();
  34. }
  35. private async void UpdateChannel()
  36. {
  37. while (true)
  38. {
  39. byte[] messageBytes;
  40. try
  41. {
  42. messageBytes = await channel.Recv();
  43. }
  44. catch (Exception e)
  45. {
  46. Log.Error(e.ToString());
  47. continue;
  48. }
  49. if (messageBytes.Length < 6)
  50. {
  51. continue;
  52. }
  53. Opcode opcode = (Opcode)BitConverter.ToUInt16(messageBytes, 0);
  54. try
  55. {
  56. this.Run(opcode, messageBytes);
  57. }
  58. catch (Exception e)
  59. {
  60. Log.Error(e.ToString());
  61. }
  62. }
  63. }
  64. private void Run(Opcode opcode, byte[] messageBytes)
  65. {
  66. int offset = 0;
  67. uint flagUInt = BitConverter.ToUInt32(messageBytes, 2);
  68. bool isCompressed = (byte)(flagUInt >> 24) == 1;
  69. if (isCompressed) // 表示有压缩,需要解压缩
  70. {
  71. messageBytes = ZipHelper.Decompress(messageBytes, 6, messageBytes.Length - 6);
  72. offset = 0;
  73. }
  74. else
  75. {
  76. offset = 6;
  77. }
  78. uint rpcId = flagUInt & 0x0fff;
  79. this.RunDecompressedBytes(opcode, rpcId, messageBytes, offset);
  80. }
  81. private void RunDecompressedBytes(Opcode opcode, uint rpcId, byte[] messageBytes, int offset)
  82. {
  83. Action<byte[], int, int> action;
  84. if (this.requestCallback.TryGetValue(rpcId, out action))
  85. {
  86. this.requestCallback.Remove(rpcId);
  87. action(messageBytes, offset, messageBytes.Length - offset);
  88. return;
  89. }
  90. if (this.waitCallback.TryGetValue(opcode, out action))
  91. {
  92. this.waitCallback.Remove(opcode);
  93. action(messageBytes, offset, messageBytes.Length - offset);
  94. return;
  95. }
  96. Server.Scene.GetComponent<MessageHandlerComponent>().Handle(this.Owner, opcode, messageBytes, offset);
  97. }
  98. public Task<Response> CallAsync<Response>(object request, CancellationToken cancellationToken) where Response : IErrorMessage
  99. {
  100. this.Send(request, ++this.RpcId);
  101. var tcs = new TaskCompletionSource<Response>();
  102. this.requestCallback[this.RpcId] = (bytes, offset, count) =>
  103. {
  104. try
  105. {
  106. Response response = MongoHelper.FromBson<Response>(bytes, offset, count);
  107. Opcode opcode = EnumHelper.FromString<Opcode>(response.GetType().Name);
  108. if (OpcodeHelper.IsNeedDebugLogMessage(opcode))
  109. {
  110. Log.Debug(MongoHelper.ToJson(response));
  111. }
  112. if (response.ErrorMessage.errno != (int)ErrorCode.ERR_Success)
  113. {
  114. tcs.SetException(new RpcException((ErrorCode)response.ErrorMessage.errno, response.ErrorMessage.msg.Utf8ToStr()));
  115. return;
  116. }
  117. tcs.SetResult(response);
  118. }
  119. catch (Exception e)
  120. {
  121. tcs.SetException(new GameException($"Rpc Error: {typeof(Response).FullName}", e));
  122. }
  123. };
  124. cancellationToken.Register(() => { this.requestCallback.Remove(this.RpcId); });
  125. return tcs.Task;
  126. }
  127. /// <summary>
  128. /// Rpc调用,发送一个消息,等待返回一个消息
  129. /// </summary>
  130. /// <typeparam name="Response"></typeparam>
  131. /// <param name="request"></param>
  132. /// <returns></returns>
  133. public Task<Response> CallAsync<Response>(object request) where Response : IErrorMessage
  134. {
  135. this.Send(request, ++this.RpcId);
  136. var tcs = new TaskCompletionSource<Response>();
  137. this.requestCallback[this.RpcId] = (bytes, offset, count) =>
  138. {
  139. try
  140. {
  141. Response response = MongoHelper.FromBson<Response>(bytes, offset, count);
  142. Opcode opcode = EnumHelper.FromString<Opcode>(response.GetType().Name);
  143. if (OpcodeHelper.IsNeedDebugLogMessage(opcode))
  144. {
  145. Log.Debug(MongoHelper.ToJson(response));
  146. }
  147. if (response.ErrorMessage.errno != (int) ErrorCode.ERR_Success)
  148. {
  149. tcs.SetException(new RpcException((ErrorCode)response.ErrorMessage.errno, response.ErrorMessage.msg.Utf8ToStr()));
  150. return;
  151. }
  152. tcs.SetResult(response);
  153. }
  154. catch (Exception e)
  155. {
  156. tcs.SetException(new GameException($"Rpc Error: {typeof(Response).FullName}", e));
  157. }
  158. };
  159. return tcs.Task;
  160. }
  161. /// <summary>
  162. /// 不发送消息,直接等待返回一个消息
  163. /// </summary>
  164. /// <typeparam name="Response"></typeparam>
  165. /// <param name="cancellationToken"></param>
  166. /// <returns></returns>
  167. public Task<Response> WaitAsync<Response>(CancellationToken cancellationToken) where Response : class
  168. {
  169. var tcs = new TaskCompletionSource<Response>();
  170. Opcode opcode = EnumHelper.FromString<Opcode>(typeof(Response).Name);
  171. this.waitCallback[opcode] = (bytes, offset, count) =>
  172. {
  173. try
  174. {
  175. Response response = MongoHelper.FromBson<Response>(bytes, offset, count);
  176. Opcode op = EnumHelper.FromString<Opcode>(response.GetType().Name);
  177. if (OpcodeHelper.IsNeedDebugLogMessage(op))
  178. {
  179. Log.Debug(MongoHelper.ToJson(response));
  180. }
  181. tcs.SetResult(response);
  182. }
  183. catch (Exception e)
  184. {
  185. tcs.SetException(new GameException($"Wait Error: {typeof(Response).FullName}", e));
  186. }
  187. };
  188. cancellationToken.Register(() => { this.waitCallback.Remove(opcode); });
  189. return tcs.Task;
  190. }
  191. /// <summary>
  192. /// 不发送消息,直接等待返回一个消息
  193. /// </summary>
  194. /// <typeparam name="Response"></typeparam>
  195. /// <returns></returns>
  196. public Task<Response> WaitAsync<Response>() where Response : class
  197. {
  198. var tcs = new TaskCompletionSource<Response>();
  199. Opcode opcode = EnumHelper.FromString<Opcode>(typeof(Response).Name);
  200. this.waitCallback[opcode] = (bytes, offset, count) =>
  201. {
  202. try
  203. {
  204. Response response = MongoHelper.FromBson<Response>(bytes, offset, count);
  205. Opcode op = EnumHelper.FromString<Opcode>(response.GetType().Name);
  206. if (OpcodeHelper.IsNeedDebugLogMessage(op))
  207. {
  208. Log.Debug(MongoHelper.ToJson(response));
  209. }
  210. tcs.SetResult(response);
  211. }
  212. catch (Exception e)
  213. {
  214. tcs.SetException(new GameException($"Wait Error: {typeof(Response).FullName}", e));
  215. }
  216. };
  217. return tcs.Task;
  218. }
  219. public void Send(object message)
  220. {
  221. this.Send(message, 0);
  222. }
  223. private void Send(object message, uint rpcId)
  224. {
  225. Opcode opcode = EnumHelper.FromString<Opcode>(message.GetType().Name);
  226. byte[] opcodeBytes = BitConverter.GetBytes((ushort)opcode);
  227. byte[] seqBytes = BitConverter.GetBytes(rpcId);
  228. byte[] messageBytes = MongoHelper.ToBson(message);
  229. if (channel == null)
  230. {
  231. throw new GameException("game channel not found!");
  232. }
  233. channel.Send(new List<byte[]> { opcodeBytes, seqBytes, messageBytes });
  234. if (OpcodeHelper.IsNeedDebugLogMessage(opcode))
  235. {
  236. Log.Debug(MongoHelper.ToJson(message));
  237. }
  238. }
  239. public override void Dispose()
  240. {
  241. if (this.Id == 0)
  242. {
  243. return;
  244. }
  245. base.Dispose();
  246. channel.Dispose();
  247. }
  248. }
  249. }