| 1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162 |
- using System;
- using Common.Base;
- using Common.Event;
- using Network;
- using TNet;
- using UNet;
- namespace Model
- {
- public class ServiceComponent: Component<World>
- {
- private IService service;
- public void Run(string host, int port, NetworkProtocol protocol = NetworkProtocol.TCP)
- {
- switch (protocol)
- {
- case NetworkProtocol.TCP:
- this.service = new TService(host, port);
- break;
- case NetworkProtocol.UDP:
- this.service = new UService(host, port);
- break;
- default:
- throw new ArgumentOutOfRangeException("protocol");
- }
- this.service.Add(this.AcceptChannel);
- this.service.Run();
- }
- /// <summary>
- /// 接收连接
- /// </summary>
- private async void AcceptChannel()
- {
- while (true)
- {
- AChannel channel = await this.service.GetChannel();
- ProcessChannel(channel);
- }
- }
- /// <summary>
- /// 接收分发封包
- /// </summary>
- /// <param name="channel"></param>
- private static async void ProcessChannel(AChannel channel)
- {
- while (true)
- {
- byte[] message = await channel.RecvAsync();
- Env env = new Env();
- env[EnvKey.Channel] = channel;
- env[EnvKey.Message] = message;
- await World.Instance.GetComponent<EventComponent<ActionAttribute>>()
- .Run(ActionType.MessageAction, env);
- }
- }
- }
- }
|