NetworkComponent.cs 4.8 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182
  1. using System;
  2. using System.Collections.Generic;
  3. using System.Threading.Tasks;
  4. using Common.Base;
  5. using Common.Helper;
  6. using Common.Network;
  7. using TNet;
  8. using UNet;
  9. namespace Model
  10. {
  11. public class NetworkComponent: Component<World>, IUpdate, IStart
  12. {
  13. private IService service;
  14. private int requestId;
  15. private readonly Dictionary<int, Action<byte[], bool>> requestCallback = new Dictionary<int, Action<byte[], bool>>();
  16. private readonly Dictionary<string, Queue<byte[]>> cache = new Dictionary<string, Queue<byte[]>>();
  17. private void Accept(string host, int port, NetworkProtocol protocol = NetworkProtocol.TCP)
  18. {
  19. switch (protocol)
  20. {
  21. case NetworkProtocol.TCP:
  22. this.service = new TService(host, port);
  23. break;
  24. case NetworkProtocol.UDP:
  25. this.service = new UService(host, port);
  26. break;
  27. default:
  28. throw new ArgumentOutOfRangeException("protocol");
  29. }
  30. this.AcceptChannel();
  31. }
  32. public void Start()
  33. {
  34. this.Accept(World.Instance.Options.Host, World.Instance.Options.Port,
  35. World.Instance.Options.Protocol);
  36. }
  37. public void Update()
  38. {
  39. this.service.Update();
  40. }
  41. /// <summary>
  42. /// 接收连接
  43. /// </summary>
  44. private async void AcceptChannel()
  45. {
  46. while (true)
  47. {
  48. AChannel channel = await this.service.GetChannel();
  49. this.ProcessChannel(channel);
  50. }
  51. }
  52. /// <summary>
  53. /// 接收分发封包
  54. /// </summary>
  55. /// <param name="channel"></param>
  56. private async void ProcessChannel(AChannel channel)
  57. {
  58. while (true)
  59. {
  60. byte[] message = await channel.RecvAsync();
  61. Env env = new Env();
  62. env[EnvKey.Channel] = channel;
  63. env[EnvKey.Message] = message;
  64. int opcode = BitConverter.ToUInt16(message, 0);
  65. // 这个区间表示消息是rpc响应消息
  66. if (MessageTypeHelper.IsRpcResponseMessage(opcode))
  67. {
  68. int id = BitConverter.ToInt32(message, 2);
  69. this.RequestCallback(channel, id, message, true);
  70. continue;
  71. }
  72. // 如果是发给client的消息,说明这是gate server,需要根据unitid查到channel,进行发送
  73. if (MessageTypeHelper.IsServerMessage(opcode))
  74. {
  75. World.Instance.GetComponent<EventComponent<EventAttribute>>().Run(EventType.GateRecvServerMessage, env);
  76. continue;
  77. }
  78. // 进行消息分发
  79. World.Instance.GetComponent<EventComponent<EventAttribute>>().Run(EventType.LogicRecvMessage, env);
  80. }
  81. }
  82. public async void SendAsync(string address, byte[] buffer)
  83. {
  84. Queue<byte[]> queue;
  85. AChannel channel;
  86. // 连接已存在
  87. if (this.service.HasChannel(address))
  88. {
  89. channel = await this.service.GetChannel(address);
  90. channel.SendAsync(buffer);
  91. return;
  92. }
  93. // 连接不存在,但是处于正在连接过程中
  94. if (this.cache.TryGetValue(address, out queue))
  95. {
  96. queue.Enqueue(buffer);
  97. return;
  98. }
  99. // 连接不存在,需要启动连接
  100. queue = new Queue<byte[]>();
  101. queue.Enqueue(buffer);
  102. this.cache[address] = queue;
  103. channel = await this.service.GetChannel(address);
  104. while (queue.Count > 0)
  105. {
  106. channel.SendAsync(queue.Dequeue());
  107. }
  108. }
  109. // 消息回调或者超时回调
  110. public void RequestCallback(AChannel channel, int id, byte[] buffer, bool isOK)
  111. {
  112. Action<byte[], bool> action;
  113. if (this.requestCallback.TryGetValue(id, out action))
  114. {
  115. action(buffer, isOK);
  116. }
  117. this.requestCallback.Remove(id);
  118. }
  119. /// <summary>
  120. /// Rpc请求
  121. /// </summary>
  122. public Task<T> Request<T, K>(AChannel channel, short type, K request, int waitTime = 0)
  123. {
  124. ++this.requestId;
  125. byte[] requestBuffer = MongoHelper.ToBson(request);
  126. byte[] typeBuffer = BitConverter.GetBytes(type);
  127. byte[] idBuffer = BitConverter.GetBytes(this.requestId);
  128. channel.SendAsync(new List<byte[]> { typeBuffer, idBuffer, requestBuffer });
  129. var tcs = new TaskCompletionSource<T>();
  130. this.requestCallback[this.requestId] = (e, b) =>
  131. {
  132. if (b)
  133. {
  134. T response = MongoHelper.FromBson<T>(e, 6);
  135. tcs.SetResult(response);
  136. }
  137. else
  138. {
  139. tcs.SetException(new Exception(string.Format("rpc timeout {0} {1}", type, MongoHelper.ToJson(request))));
  140. }
  141. };
  142. if (waitTime > 0)
  143. {
  144. this.service.Timer.Add(TimeHelper.Now() + waitTime, () =>
  145. {
  146. this.RequestCallback(channel, this.requestId, null, false);
  147. });
  148. }
  149. return tcs.Task;
  150. }
  151. /// <summary>
  152. /// Rpc响应
  153. /// </summary>
  154. public void Response<T>(AChannel channel, short type, int id, T response)
  155. {
  156. byte[] responseBuffer = MongoHelper.ToBson(response);
  157. byte[] typeBuffer = BitConverter.GetBytes(type);
  158. byte[] idBuffer = BitConverter.GetBytes(id);
  159. channel.SendAsync(new List<byte[]> { typeBuffer, idBuffer, responseBuffer });
  160. }
  161. }
  162. }