NetworkComponent.cs 1.9 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182
  1. using System;
  2. using Common.Base;
  3. using Common.Network;
  4. using TNet;
  5. using UNet;
  6. namespace Model
  7. {
  8. public class NetworkComponent: Component<World>, IUpdate, IStart
  9. {
  10. private IService service;
  11. private void Accept(string host, int port, NetworkProtocol protocol = NetworkProtocol.TCP)
  12. {
  13. switch (protocol)
  14. {
  15. case NetworkProtocol.TCP:
  16. this.service = new TService(host, port);
  17. break;
  18. case NetworkProtocol.UDP:
  19. this.service = new UService(host, port);
  20. break;
  21. default:
  22. throw new ArgumentOutOfRangeException("protocol");
  23. }
  24. this.AcceptChannel();
  25. }
  26. public void Start()
  27. {
  28. this.Accept(World.Instance.Options.Host, World.Instance.Options.Port,
  29. World.Instance.Options.Protocol);
  30. }
  31. public void Update()
  32. {
  33. this.service.Update();
  34. }
  35. /// <summary>
  36. /// 接收连接
  37. /// </summary>
  38. private async void AcceptChannel()
  39. {
  40. while (true)
  41. {
  42. AChannel channel = await this.service.GetChannel();
  43. ProcessChannel(channel);
  44. }
  45. }
  46. /// <summary>
  47. /// 接收分发封包
  48. /// </summary>
  49. /// <param name="channel"></param>
  50. private static async void ProcessChannel(AChannel channel)
  51. {
  52. while (true)
  53. {
  54. byte[] message = await channel.RecvAsync();
  55. Env env = new Env();
  56. env[EnvKey.Channel] = channel;
  57. env[EnvKey.Message] = message;
  58. int opcode = BitConverter.ToUInt16(message, 0);
  59. // 这个区间表示消息是rpc响应消息
  60. if (opcode >= 40000 && opcode < 50000)
  61. {
  62. int id = BitConverter.ToInt32(message, 2);
  63. channel.RequestCallback(id, message, true);
  64. continue;
  65. }
  66. // 进行消息解析分发
  67. #pragma warning disable 4014
  68. World.Instance.GetComponent<EventComponent<EventAttribute>>()
  69. .RunAsync(EventType.Message, env);
  70. #pragma warning restore 4014
  71. }
  72. }
  73. }
  74. }