NetworkComponent.cs 5.1 KB

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