MessageComponent.cs 6.5 KB

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