| 123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442 |
- using System;
- using System.Collections.Generic;
- using System.Linq;
- using System.Reflection;
- using System.Threading;
- using System.Threading.Tasks;
- namespace Base
- {
- public enum NetChannelType
- {
- Login,
- Gate,
- Battle,
- }
- [ObjectEvent]
- public class MessageComponentEvent : ObjectEvent<MessageComponent>, ILoader, IAwake<SceneType>, IUpdate
- {
- public void Load()
- {
- this.GetValue().Load();
- }
- public void Awake(SceneType sceneType)
- {
- this.GetValue().Awake(sceneType);
- }
- public void Update()
- {
- this.GetValue().Update();
- }
- }
-
- /// <summary>
- /// 消息分发组件
- /// </summary>
- public class MessageComponent: Component
- {
- private SceneType SceneType;
- private uint RpcId { get; set; }
- private Dictionary<Opcode, List<Action<byte[], int, int>>> events;
- private readonly Dictionary<uint, Action<byte[], int, int>> requestCallback = new Dictionary<uint, Action<byte[], int, int>>();
- private readonly Dictionary<Opcode, Action<byte[], int, int>> waitCallback = new Dictionary<Opcode, Action<byte[], int, int>>();
- private readonly Dictionary<NetChannelType, AChannel> channels = new Dictionary<NetChannelType, AChannel>();
-
- public void Awake(SceneType sceneType)
- {
- this.SceneType = sceneType;
- this.Load();
- }
- public void Load()
- {
- this.events = new Dictionary<Opcode, List<Action<byte[], int, int>>>();
- Assembly[] assemblies = Object.ObjectManager.GetAssemblies();
- foreach (Assembly assembly in assemblies)
- {
- Type[] types = assembly.GetTypes();
- foreach (Type type in types)
- {
- object[] attrs = type.GetCustomAttributes(typeof(MessageAttribute), false);
- if (attrs.Length == 0)
- {
- continue;
- }
- MessageAttribute messageAttribute = (MessageAttribute)attrs[0];
- if (messageAttribute.SceneType != this.SceneType)
- {
- continue;
- }
- object obj = Activator.CreateInstance(type);
- IMRegister<MessageComponent> iMRegister = obj as IMRegister<MessageComponent>;
- if (iMRegister == null)
- {
- throw new GameException($"message handler not inherit IEventSync or IEventAsync interface: {obj.GetType().FullName}");
- }
- iMRegister.Register(this);
- }
- }
- }
- public void Register<T>(Action<Entity, T> action)
- {
- Opcode opcode = EnumHelper.FromString<Opcode>(typeof (T).Name);
- if (!this.events.ContainsKey(opcode))
- {
- this.events.Add(opcode, new List<Action<byte[], int, int>>());
- }
- List<Action<byte[], int, int>> actions = this.events[opcode];
- actions.Add((messageBytes, offset, count) =>
- {
- T t;
- try
- {
- t = MongoHelper.FromBson<T>(messageBytes, offset, count);
- }
- catch (Exception ex)
- {
- throw new GameException("解释消息失败:" + opcode, ex);
- }
- if (OpcodeHelper.IsNeedDebugLogMessage(opcode))
- {
- Log.Debug(MongoHelper.ToJson(t));
- }
- action(this.Owner, t);
- });
- }
- public void Connect(NetChannelType channelType, string host, int port)
- {
- AChannel channel = Share.Scene.GetComponent<NetworkComponent>().ConnectChannel(host, port);
- this.channels[channelType] = channel;
- }
- public void Close(NetChannelType channelType)
- {
- AChannel channel = this.GetChannel(channelType);
- if (channel == null || channel.Id == 0)
- {
- return;
- }
- this.channels.Remove(channelType);
- channel.Dispose();
- }
- public void Update()
- {
- foreach (AChannel channel in this.channels.Values.ToArray())
- {
- this.UpdateChannel(channel);
- }
- }
- private void UpdateChannel(AChannel channel)
- {
- if (channel.Id == 0)
- {
- return;
- }
- while (true)
- {
- byte[] messageBytes = channel.Recv();
- if (messageBytes == null)
- {
- return;
- }
- if (messageBytes.Length < 6)
- {
- continue;
- }
- Opcode opcode = (Opcode)BitConverter.ToUInt16(messageBytes, 0);
- try
- {
- this.Run(opcode, messageBytes);
- }
- catch (Exception e)
- {
- Log.Error(e.ToString());
- }
- }
- }
- public void Run(Opcode opcode, byte[] messageBytes)
- {
- int offset = 0;
- uint flagUInt = BitConverter.ToUInt32(messageBytes, 2);
- bool isCompressed = (byte)(flagUInt >> 24) == 1;
- if (isCompressed) // 表示有压缩,需要解压缩
- {
- messageBytes = ZipHelper.Decompress(messageBytes, 6, messageBytes.Length - 6);
- offset = 0;
- }
- else
- {
- offset = 6;
- }
- uint rpcId = flagUInt & 0x0fff;
- this.RunDecompressedBytes(opcode, rpcId, messageBytes, offset);
- }
- public void RunDecompressedBytes(Opcode opcode, uint rpcId, byte[] messageBytes, int offset)
- {
- Action<byte[], int, int> action;
- if (this.requestCallback.TryGetValue(rpcId, out action))
- {
- this.requestCallback.Remove(rpcId);
- action(messageBytes, offset, messageBytes.Length - offset);
- return;
- }
- if (this.waitCallback.TryGetValue(opcode, out action))
- {
- this.waitCallback.Remove(opcode);
- action(messageBytes, offset, messageBytes.Length - offset);
- return;
- }
- List<Action<byte[], int, int>> actions;
- if (!this.events.TryGetValue(opcode, out actions))
- {
- if (this.SceneType == SceneType.Game)
- {
- Log.Error($"消息{opcode}没有处理");
- }
- return;
- }
- foreach (var ev in actions)
- {
- try
- {
- ev(messageBytes, offset, messageBytes.Length - offset);
- }
- catch (Exception e)
- {
- Log.Error(e.ToString());
- }
- }
- }
- public Task<Response> CallAsync<Response>(object request, CancellationToken cancellationToken) where Response : IErrorMessage
- {
- this.Send(request, ++this.RpcId);
- var tcs = new TaskCompletionSource<Response>();
- this.requestCallback[this.RpcId] = (bytes, offset, count) =>
- {
- try
- {
- Response response = MongoHelper.FromBson<Response>(bytes, offset, count);
- Opcode opcode = EnumHelper.FromString<Opcode>(response.GetType().Name);
- if (OpcodeHelper.IsNeedDebugLogMessage(opcode))
- {
- Log.Debug(MongoHelper.ToJson(response));
- }
- if (response.ErrorMessage.errno != (int)ErrorCode.ERR_Success)
- {
- tcs.SetException(new RpcException((ErrorCode)response.ErrorMessage.errno, response.ErrorMessage.msg.Utf8ToStr()));
- return;
- }
- tcs.SetResult(response);
- }
- catch (Exception e)
- {
- tcs.SetException(new GameException($"Rpc Error: {typeof(Response).FullName}", e));
- }
- };
- cancellationToken.Register(() => { this.requestCallback.Remove(this.RpcId); });
- return tcs.Task;
- }
- /// <summary>
- /// Rpc调用,发送一个消息,等待返回一个消息
- /// </summary>
- /// <typeparam name="Response"></typeparam>
- /// <param name="request"></param>
- /// <returns></returns>
- public Task<Response> CallAsync<Response>(object request) where Response : IErrorMessage
- {
- this.Send(request, ++this.RpcId);
- var tcs = new TaskCompletionSource<Response>();
- this.requestCallback[this.RpcId] = (bytes, offset, count) =>
- {
- try
- {
- Response response = MongoHelper.FromBson<Response>(bytes, offset, count);
- Opcode opcode = EnumHelper.FromString<Opcode>(response.GetType().Name);
- if (OpcodeHelper.IsNeedDebugLogMessage(opcode))
- {
- Log.Debug(MongoHelper.ToJson(response));
- }
- if (response.ErrorMessage.errno != (int) ErrorCode.ERR_Success)
- {
- tcs.SetException(new RpcException((ErrorCode)response.ErrorMessage.errno, response.ErrorMessage.msg.Utf8ToStr()));
- return;
- }
- tcs.SetResult(response);
- }
- catch (Exception e)
- {
- tcs.SetException(new GameException($"Rpc Error: {typeof(Response).FullName}", e));
- }
- };
-
- return tcs.Task;
- }
- /// <summary>
- /// 不发送消息,直接等待返回一个消息
- /// </summary>
- /// <typeparam name="Response"></typeparam>
- /// <param name="cancellationToken"></param>
- /// <returns></returns>
- public Task<Response> WaitAsync<Response>(CancellationToken cancellationToken) where Response : class
- {
- var tcs = new TaskCompletionSource<Response>();
- Opcode opcode = EnumHelper.FromString<Opcode>(typeof(Response).Name);
- this.waitCallback[opcode] = (bytes, offset, count) =>
- {
- try
- {
- Response response = MongoHelper.FromBson<Response>(bytes, offset, count);
- Opcode op = EnumHelper.FromString<Opcode>(response.GetType().Name);
- if (OpcodeHelper.IsNeedDebugLogMessage(op))
- {
- Log.Debug(MongoHelper.ToJson(response));
- }
-
- tcs.SetResult(response);
- }
- catch (Exception e)
- {
- tcs.SetException(new GameException($"Wait Error: {typeof(Response).FullName}", e));
- }
- };
- cancellationToken.Register(() => { this.waitCallback.Remove(opcode); });
- return tcs.Task;
- }
- /// <summary>
- /// 不发送消息,直接等待返回一个消息
- /// </summary>
- /// <typeparam name="Response"></typeparam>
- /// <returns></returns>
- public Task<Response> WaitAsync<Response>() where Response : class
- {
- var tcs = new TaskCompletionSource<Response>();
- Opcode opcode = EnumHelper.FromString<Opcode>(typeof(Response).Name);
- this.waitCallback[opcode] = (bytes, offset, count) =>
- {
- try
- {
- Response response = MongoHelper.FromBson<Response>(bytes, offset, count);
- Opcode op = EnumHelper.FromString<Opcode>(response.GetType().Name);
- if (OpcodeHelper.IsNeedDebugLogMessage(op))
- {
- Log.Debug(MongoHelper.ToJson(response));
- }
- tcs.SetResult(response);
- }
- catch (Exception e)
- {
- tcs.SetException(new GameException($"Wait Error: {typeof(Response).FullName}", e));
- }
- };
- return tcs.Task;
- }
- public AChannel GetChannel(NetChannelType channelType)
- {
- AChannel channel;
- this.channels.TryGetValue(channelType, out channel);
- return channel;
- }
- public void Send(object message)
- {
- this.Send(message, 0);
- }
- public bool IsChannelConnected(NetChannelType channelType)
- {
- AChannel channel = GetChannel(channelType);
- if (channel == null)
- {
- return false;
- }
- return true;
- }
- private void Send(object message, uint rpcId)
- {
- Opcode opcode = EnumHelper.FromString<Opcode>(message.GetType().Name);
- byte[] opcodeBytes = BitConverter.GetBytes((ushort)opcode);
- byte[] seqBytes = BitConverter.GetBytes(rpcId);
- byte[] messageBytes = MongoHelper.ToBson(message);
- NetChannelType channelType;
- if ((ushort)opcode > 7000 && (ushort)opcode < 8000)
- {
- channelType = NetChannelType.Login;
- }
- else if ((ushort)opcode > 0 && (ushort)opcode <= 1000)
- {
- channelType = NetChannelType.Battle;
- }
- else
- {
- channelType = NetChannelType.Gate;
- }
- AChannel channel = this.GetChannel(channelType);
- if (channel == null)
- {
- throw new GameException("game channel not found!");
- }
- channel.Send(new List<byte[]> { opcodeBytes, seqBytes, messageBytes });
- if (OpcodeHelper.IsNeedDebugLogMessage(opcode))
- {
- Log.Debug(MongoHelper.ToJson(message));
- }
- }
- public override void Dispose()
- {
- if (this.Id == 0)
- {
- return;
- }
- base.Dispose();
- foreach (AChannel channel in this.channels.Values.ToArray())
- {
- channel.Dispose();
- }
- }
- }
- }
|