NetworkComponent.cs 3.8 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149
  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 MongoDB.Bson;
  8. using TNet;
  9. using UNet;
  10. namespace Model
  11. {
  12. public class NetworkComponent: Component<World>, IUpdate, IStart
  13. {
  14. private IService service;
  15. private int requestId;
  16. private readonly Dictionary<int, Action<byte[], bool>> requestCallback = new Dictionary<int, Action<byte[], bool>>();
  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. // 进行消息分发
  73. World.Instance.GetComponent<EventComponent<EventAttribute>>().Run(EventType.GateMessage, env);
  74. }
  75. }
  76. public async void SendAsync(string address, byte[] buffer)
  77. {
  78. }
  79. // 消息回调或者超时回调
  80. public void RequestCallback(AChannel channel, int id, byte[] buffer, bool isOK)
  81. {
  82. Action<byte[], bool> action;
  83. if (this.requestCallback.TryGetValue(id, out action))
  84. {
  85. action(buffer, isOK);
  86. }
  87. this.requestCallback.Remove(id);
  88. }
  89. /// <summary>
  90. /// Rpc请求
  91. /// </summary>
  92. public Task<T> Request<T, K>(AChannel channel, short type, K request, int waitTime = 0)
  93. {
  94. ++this.requestId;
  95. byte[] requestBuffer = MongoHelper.ToBson(request);
  96. byte[] typeBuffer = BitConverter.GetBytes(type);
  97. byte[] idBuffer = BitConverter.GetBytes(this.requestId);
  98. channel.SendAsync(new List<byte[]> { typeBuffer, idBuffer, requestBuffer });
  99. var tcs = new TaskCompletionSource<T>();
  100. this.requestCallback[this.requestId] = (e, b) =>
  101. {
  102. if (b)
  103. {
  104. T response = MongoHelper.FromBson<T>(e, 6);
  105. tcs.SetResult(response);
  106. }
  107. else
  108. {
  109. tcs.SetException(new Exception(string.Format("rpc timeout {0} {1}", type, MongoHelper.ToJson(request))));
  110. }
  111. };
  112. if (waitTime > 0)
  113. {
  114. this.service.Timer.Add(TimeHelper.Now() + waitTime, () =>
  115. {
  116. this.RequestCallback(channel, this.requestId, null, false);
  117. });
  118. }
  119. return tcs.Task;
  120. }
  121. /// <summary>
  122. /// Rpc响应
  123. /// </summary>
  124. public void Response<T>(AChannel channel, short type, int id, T response)
  125. {
  126. byte[] responseBuffer = MongoHelper.ToBson(response);
  127. byte[] typeBuffer = BitConverter.GetBytes(type);
  128. byte[] idBuffer = BitConverter.GetBytes(id);
  129. channel.SendAsync(new List<byte[]> { typeBuffer, idBuffer, responseBuffer });
  130. }
  131. }
  132. }