MessageComponent.cs 9.7 KB

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