MessageComponent.cs 5.4 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238
  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. // 普通消息
  92. if (rpcId == 0)
  93. {
  94. this.messageDispather.Handle(this.Owner, opcode, messageBytes, offset);
  95. return;
  96. }
  97. // rpcFlag>0 表示这是一个rpc响应消息
  98. if (rpcFlag > 0)
  99. {
  100. Action<byte[], int, int> action;
  101. // Rpc回调有找不着的可能,因为client可能取消Rpc调用
  102. if (!this.requestCallback.TryGetValue(rpcId, out action))
  103. {
  104. return;
  105. }
  106. this.requestCallback.Remove(rpcId);
  107. action(messageBytes, offset, messageBytes.Length - offset);
  108. }
  109. else // 这是一个rpc请求消息
  110. {
  111. this.messageDispather.HandleRpc(this.Owner, opcode, messageBytes, offset, rpcId);
  112. }
  113. }
  114. /// <summary>
  115. /// Rpc调用
  116. /// </summary>
  117. public Task<Response> Call<Request, Response>(Request request, CancellationToken cancellationToken)
  118. where Request : ARequest
  119. where Response : AResponse
  120. {
  121. this.SendMessage(++RpcId, request);
  122. var tcs = new TaskCompletionSource<Response>();
  123. this.requestCallback[RpcId] = (bytes, offset, count) =>
  124. {
  125. try
  126. {
  127. Response response = MongoHelper.FromBson<Response>(bytes, offset, count);
  128. if (response.ErrorCode != 0)
  129. {
  130. tcs.SetException(new RpcException(response.ErrorCode, response.Message));
  131. return;
  132. }
  133. tcs.SetResult(response);
  134. }
  135. catch (Exception e)
  136. {
  137. tcs.SetException(new Exception($"Rpc Error: {typeof(Response).FullName}", e));
  138. }
  139. };
  140. cancellationToken.Register(() => { this.requestCallback.Remove(RpcId); });
  141. return tcs.Task;
  142. }
  143. /// <summary>
  144. /// Rpc调用,发送一个消息,等待返回一个消息
  145. /// </summary>
  146. public Task<Response> Call<Request, Response>(Request request)
  147. where Request: ARequest
  148. where Response : AResponse
  149. {
  150. this.SendMessage(++RpcId, request);
  151. var tcs = new TaskCompletionSource<Response>();
  152. this.requestCallback[RpcId] = (bytes, offset, count) =>
  153. {
  154. try
  155. {
  156. Response response = MongoHelper.FromBson<Response>(bytes, offset, count);
  157. if (response.ErrorCode != 0)
  158. {
  159. tcs.SetException(new RpcException(response.ErrorCode, response.Message));
  160. return;
  161. }
  162. tcs.SetResult(response);
  163. }
  164. catch (Exception e)
  165. {
  166. tcs.SetException(new Exception($"Rpc Error: {typeof(Response).FullName}", e));
  167. }
  168. };
  169. return tcs.Task;
  170. }
  171. public void Send<Message>(Message message) where Message: AMessage
  172. {
  173. this.SendMessage(0, message);
  174. }
  175. public void Reply<Response>(uint rpcId, Response message) where Response: AResponse
  176. {
  177. this.SendMessage(rpcId, message, false);
  178. }
  179. private void SendMessage(uint rpcId, object message, bool isCall = true)
  180. {
  181. ushort opcode = this.messageDispather.GetOpcode(message.GetType());
  182. byte[] opcodeBytes = BitConverter.GetBytes(opcode);
  183. if (!isCall)
  184. {
  185. rpcId = rpcId | 0x40000000;
  186. }
  187. byte[] messageBytes = MongoHelper.ToBson(message);
  188. if (messageBytes.Length > 100)
  189. {
  190. byte[] newMessageBytes = ZipHelper.Compress(messageBytes);
  191. if (newMessageBytes.Length < messageBytes.Length)
  192. {
  193. messageBytes = newMessageBytes;
  194. rpcId = rpcId | 0x80000000;
  195. }
  196. }
  197. byte[] seqBytes = BitConverter.GetBytes(rpcId);
  198. channel.Send(new List<byte[]> { opcodeBytes, seqBytes, messageBytes });
  199. }
  200. public override void Dispose()
  201. {
  202. if (this.Id == 0)
  203. {
  204. return;
  205. }
  206. base.Dispose();
  207. channel.Dispose();
  208. }
  209. }
  210. }