| 123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334 |
- using System;
- using System.Collections.Generic;
- using System.Net;
- using System.Threading;
- using System.Threading.Tasks;
- namespace Model
- {
- [ObjectEvent]
- public class SessionSystem : ObjectSystem<Session>, IAwake<NetworkComponent, AChannel>, IStart
- {
- public void Awake(NetworkComponent network, AChannel channel)
- {
- this.Get().Awake(network, channel);
- }
- public void Start()
- {
- this.Get().Start();
- }
- }
- public sealed class Session : Entity
- {
- private static uint RpcId { get; set; }
- private NetworkComponent network;
- private AChannel channel;
- private readonly Dictionary<uint, Action<object>> requestCallback = new Dictionary<uint, Action<object>>();
- private readonly List<byte[]> byteses = new List<byte[]>() {new byte[0], new byte[0]};
-
- public void Awake(NetworkComponent net, AChannel c)
- {
- this.network = net;
- this.channel = c;
- this.requestCallback.Clear();
- }
- public void Start()
- {
- this.StartRecv();
- }
- public override void Dispose()
- {
- if (this.Id == 0)
- {
- return;
- }
- long id = this.Id;
- base.Dispose();
- this.channel.Dispose();
- this.network.Remove(id);
- this.requestCallback.Clear();
- }
- public IPEndPoint RemoteAddress
- {
- get
- {
- return this.channel.RemoteAddress;
- }
- }
- public ChannelType ChannelType
- {
- get
- {
- return this.channel.ChannelType;
- }
- }
- private async void StartRecv()
- {
- while (true)
- {
- if (this.Id == 0)
- {
- return;
- }
- Packet packet;
- try
- {
- packet = await this.channel.Recv();
- if (this.Id == 0)
- {
- return;
- }
- }
- catch (Exception e)
- {
- Log.Error(e.ToString());
- continue;
- }
- if (packet.Length < 2)
- {
- Log.Error($"message error length < 2, ip: {this.RemoteAddress}");
- this.network.Remove(this.Id);
- return;
- }
- ushort opcode = BitConverter.ToUInt16(packet.Bytes, 0);
- try
- {
- this.RunDecompressedBytes(opcode, packet.Bytes, 2, packet.Length);
- }
- catch (Exception e)
- {
- Log.Error(e.ToString());
- }
- }
- }
- private void RunDecompressedBytes(ushort opcode, byte[] messageBytes, int offset, int count)
- {
- object message;
- Opcode op;
- try
- {
- op = (Opcode)opcode;
- Type messageType = this.network.Parent.GetComponent<OpcodeTypeComponent>().GetType(op);
- message = this.network.MessagePacker.DeserializeFrom(messageType, messageBytes, offset, count - offset);
- }
- catch (Exception e)
- {
- Log.Error($"message deserialize error, ip: {this.RemoteAddress} {opcode} {e}");
- this.network.Remove(this.Id);
- return;
- }
- //Log.Debug($"recv: {MongoHelper.ToJson(message)}");
- AResponse response = message as AResponse;
- if (response != null)
- {
- // rpcFlag>0 表示这是一个rpc响应消息
- // Rpc回调有找不着的可能,因为client可能取消Rpc调用
- Action<object> action;
- if (!this.requestCallback.TryGetValue(response.RpcId, out action))
- {
- return;
- }
- this.requestCallback.Remove(response.RpcId);
- action(message);
- return;
- }
- this.network.MessageDispatcher.Dispatch(this, op, offset, messageBytes, (AMessage)message);
- }
- /// <summary>
- /// Rpc调用,发送一个消息,等待返回一个消息
- /// </summary>
- public Task<AResponse> Call(ARequest request, bool isHotfix)
- {
- request.RpcId = ++RpcId;
- var tcs = new TaskCompletionSource<AResponse>();
- this.requestCallback[request.RpcId] = (message) =>
- {
- try
- {
- AResponse response = (AResponse)message;
- if (response.Error > 100)
- {
- tcs.SetException(new RpcException(response.Error, response.Message));
- return;
- }
- //Log.Debug($"recv: {MongoHelper.ToJson(response)}");
- tcs.SetResult(response);
- }
- catch (Exception e)
- {
- tcs.SetException(new Exception($"Rpc Error: {message.GetType().FullName}", e));
- }
- };
- this.SendMessage(request);
- return tcs.Task;
- }
- /// <summary>
- /// Rpc调用
- /// </summary>
- public Task<AResponse> Call(ARequest request, bool isHotfix, CancellationToken cancellationToken)
- {
- request.RpcId = ++RpcId;
-
- var tcs = new TaskCompletionSource<AResponse>();
- this.requestCallback[request.RpcId] = (message) =>
- {
- try
- {
- AResponse response = (AResponse)message;
- if (response.Error > 100)
- {
- tcs.SetException(new RpcException(response.Error, response.Message));
- return;
- }
- //Log.Debug($"recv: {MongoHelper.ToJson(response)}");
- tcs.SetResult(response);
- }
- catch (Exception e)
- {
- tcs.SetException(new Exception($"Rpc Error: {message.GetType().FullName}", e));
- }
- };
- cancellationToken.Register(() => { this.requestCallback.Remove(request.RpcId); });
- this.SendMessage(request);
- return tcs.Task;
- }
- /// <summary>
- /// Rpc调用,发送一个消息,等待返回一个消息
- /// </summary>
- public Task<Response> Call<Response>(ARequest request) where Response : AResponse
- {
- request.RpcId = ++RpcId;
-
- var tcs = new TaskCompletionSource<Response>();
- this.requestCallback[request.RpcId] = (message) =>
- {
- try
- {
- Response response = (Response)message;
- if (response.Error > 100)
- {
- tcs.SetException(new RpcException(response.Error, response.Message));
- return;
- }
- //Log.Debug($"recv: {MongoHelper.ToJson(response)}");
- tcs.SetResult(response);
- }
- catch (Exception e)
- {
- tcs.SetException(new Exception($"Rpc Error: {typeof(Response).FullName}", e));
- }
- };
- this.SendMessage(request);
- return tcs.Task;
- }
- /// <summary>
- /// Rpc调用
- /// </summary>
- public Task<Response> Call<Response>(ARequest request, CancellationToken cancellationToken)
- where Response : AResponse
- {
- request.RpcId = ++RpcId;
-
- var tcs = new TaskCompletionSource<Response>();
- this.requestCallback[request.RpcId] = (message) =>
- {
- try
- {
- Response response = (Response)message;
- if (response.Error > 100)
- {
- tcs.SetException(new RpcException(response.Error, response.Message));
- return;
- }
- //Log.Debug($"recv: {MongoHelper.ToJson(response)}");
- tcs.SetResult(response);
- }
- catch (Exception e)
- {
- tcs.SetException(new Exception($"Rpc Error: {typeof(Response).FullName}", e));
- }
- };
- cancellationToken.Register(() => { this.requestCallback.Remove(request.RpcId); });
- this.SendMessage(request);
- return tcs.Task;
- }
- public void Send(AMessage message)
- {
- if (this.Id == 0)
- {
- throw new Exception("session已经被Dispose了");
- }
- this.SendMessage(message);
- }
- public void Reply<Response>(Response message) where Response : AResponse
- {
- if (this.Id == 0)
- {
- throw new Exception("session已经被Dispose了");
- }
- this.SendMessage(message);
- }
- private void SendMessage(object message)
- {
- //Log.Debug($"send: {MongoHelper.ToJson(message)}");
- Opcode opcode = this.network.Parent.GetComponent<OpcodeTypeComponent>().GetOpcode(message.GetType());
- ushort op = (ushort)opcode;
- byte[] messageBytes = this.network.MessagePacker.SerializeToByteArray(message);
- #if SERVER
- // 如果是allserver,内部消息不走网络,直接转给session,方便调试时看到整体堆栈
- if (this.network.AppType == AppType.AllServer)
- {
- Session session = this.network.Parent.GetComponent<NetInnerComponent>().Get(this.RemoteAddress);
- session.RunDecompressedBytes(op, messageBytes, 0, messageBytes.Length);
- return;
- }
- #endif
- byte[] opcodeBytes = BitConverter.GetBytes(op);
-
- this.byteses[0] = opcodeBytes;
- this.byteses[1] = messageBytes;
- channel.Send(this.byteses);
- }
- }
- }
|