MessageComponent.cs 5.1 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229
  1. using System;
  2. using System.Collections.Generic;
  3. using System.Threading;
  4. using System.Threading.Tasks;
  5. using Base;
  6. namespace Model
  7. {
  8. [ObjectEvent]
  9. public class MessageComponentEvent : ObjectEvent<MessageComponent>, IAwake<AChannel>
  10. {
  11. public void Awake(AChannel aChannel)
  12. {
  13. this.GetValue().Awake(aChannel);
  14. }
  15. }
  16. /// <summary>
  17. /// 消息收发
  18. /// </summary>
  19. public class MessageComponent: Component
  20. {
  21. private static uint RpcId { get; set; }
  22. private readonly Dictionary<uint, Action<byte[], int, int>> requestCallback = new Dictionary<uint, Action<byte[], int, int>>();
  23. private AChannel channel;
  24. private MessageDispatherComponent messageDispather;
  25. public void Awake(AChannel aChannel)
  26. {
  27. this.messageDispather = Game.Scene.GetComponent<MessageDispatherComponent>();
  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 flag = BitConverter.ToUInt32(messageBytes, 2);
  75. uint rpcFlag = flag & 0x40000000;
  76. uint rpcId = flag & 0x3fffffff;
  77. bool isCompressed = (flag & 0x80000000) > 0;
  78. if (isCompressed) // 最高位为1,表示有压缩,需要解压缩
  79. {
  80. messageBytes = ZipHelper.Decompress(messageBytes, 6, messageBytes.Length - 6);
  81. offset = 0;
  82. }
  83. else
  84. {
  85. offset = 6;
  86. }
  87. this.RunDecompressedBytes(opcode, rpcId, rpcFlag, messageBytes, offset);
  88. }
  89. private void RunDecompressedBytes(ushort opcode, uint rpcId, uint rpcFlag, byte[] messageBytes, int offset)
  90. {
  91. if (rpcId == 0)
  92. {
  93. this.messageDispather.Handle(this.Owner, opcode, messageBytes, offset);
  94. }
  95. // rpcFlag>0 表示这是一个rpc响应消息
  96. if (rpcFlag > 0)
  97. {
  98. Action<byte[], int, int> action;
  99. if (this.requestCallback.TryGetValue(rpcId, out action))
  100. {
  101. this.requestCallback.Remove(rpcId);
  102. action(messageBytes, offset, messageBytes.Length - offset);
  103. }
  104. }
  105. else // 这是一个rpc请求消息
  106. {
  107. this.messageDispather.HandleRpc(this.Owner, opcode, messageBytes, offset, rpcId);
  108. }
  109. }
  110. /// <summary>
  111. /// Rpc调用
  112. /// </summary>
  113. public Task<Response> Call<Request, Response>(Request request, CancellationToken cancellationToken)
  114. where Request : ARequest
  115. where Response : AResponse
  116. {
  117. this.SendMessage(++RpcId, request);
  118. var tcs = new TaskCompletionSource<Response>();
  119. this.requestCallback[RpcId] = (bytes, offset, count) =>
  120. {
  121. try
  122. {
  123. Response response = MongoHelper.FromBson<Response>(bytes, offset, count);
  124. if (response.ErrorCode != 0)
  125. {
  126. tcs.SetException(new RpcException(response.ErrorCode, response.Message));
  127. return;
  128. }
  129. tcs.SetResult(response);
  130. }
  131. catch (Exception e)
  132. {
  133. tcs.SetException(new Exception($"Rpc Error: {typeof(Response).FullName}", e));
  134. }
  135. };
  136. cancellationToken.Register(() => { this.requestCallback.Remove(RpcId); });
  137. return tcs.Task;
  138. }
  139. /// <summary>
  140. /// Rpc调用,发送一个消息,等待返回一个消息
  141. /// </summary>
  142. public Task<Response> Call<Request, Response>(Request request)
  143. where Request: ARequest
  144. where Response : AResponse
  145. {
  146. request.RpcId = ++RpcId;
  147. this.SendMessage(++RpcId, request);
  148. var tcs = new TaskCompletionSource<Response>();
  149. this.requestCallback[RpcId] = (bytes, offset, count) =>
  150. {
  151. try
  152. {
  153. Response response = MongoHelper.FromBson<Response>(bytes, offset, count);
  154. if (response.ErrorCode != 0)
  155. {
  156. tcs.SetException(new RpcException(response.ErrorCode, response.Message));
  157. return;
  158. }
  159. tcs.SetResult(response);
  160. }
  161. catch (Exception e)
  162. {
  163. tcs.SetException(new Exception($"Rpc Error: {typeof(Response).FullName}", e));
  164. }
  165. };
  166. return tcs.Task;
  167. }
  168. public void Send(object message)
  169. {
  170. this.SendMessage(0, message);
  171. }
  172. public void Reply<T>(uint rpcId, T message) where T: AResponse
  173. {
  174. this.SendMessage(rpcId, message, false);
  175. }
  176. private void SendMessage(uint rpcId, object message, bool isCall = true)
  177. {
  178. ushort opcode = this.messageDispather.GetOpcode(message.GetType());
  179. byte[] opcodeBytes = BitConverter.GetBytes(opcode);
  180. if (rpcId > 0 && !isCall)
  181. {
  182. rpcId = rpcId | 0x4fffffff;
  183. }
  184. byte[] seqBytes = BitConverter.GetBytes(rpcId);
  185. byte[] messageBytes = MongoHelper.ToBson(message);
  186. if (channel == null)
  187. {
  188. throw new Exception("game channel not found!");
  189. }
  190. channel.Send(new List<byte[]> { opcodeBytes, seqBytes, messageBytes });
  191. }
  192. public override void Dispose()
  193. {
  194. if (this.Id == 0)
  195. {
  196. return;
  197. }
  198. base.Dispose();
  199. channel.Dispose();
  200. }
  201. }
  202. }