private void SendMessage(uint rpcId, object message, bool isCall = true) { ushort opcode = this.network.Owner.GetComponent <MessageDispatherComponent>().GetOpcode(message.GetType()); byte[] opcodeBytes = BitConverter.GetBytes(opcode); if (!isCall) { rpcId = rpcId | 0x40000000; } byte[] messageBytes = MongoHelper.ToBson(message); if (messageBytes.Length > 100) { byte[] newMessageBytes = ZipHelper.Compress(messageBytes); if (newMessageBytes.Length < messageBytes.Length) { messageBytes = newMessageBytes; rpcId = rpcId | 0x80000000; } } byte[] seqBytes = BitConverter.GetBytes(rpcId); channel.Send(new List <byte[]> { opcodeBytes, seqBytes, messageBytes }); }
public void Register <T, R>(Func <T, R> func) { Opcode opcode = EnumHelper.FromString <Opcode>(typeof(T).Name); events.Add(opcode, messageBytes => { T t = MongoHelper.FromBson <T>(messageBytes, 6); R k = func(t); return(MongoHelper.ToBson(k)); }); }
/// <summary> /// Rpc请求 /// </summary> public Task <T> RpcCall <T, K>(string address, K request, int waitTime = 0) { AChannel channel = this.service.GetChannel(address); ++this.requestId; byte[] requestBuffer = MongoHelper.ToBson(request); Opcode opcode = EnumHelper.FromString <Opcode>(request.GetType().Name); byte[] opcodeBuffer = BitConverter.GetBytes((ushort)opcode); byte[] idBuffer = BitConverter.GetBytes(this.requestId); channel.SendAsync(new List <byte[]> { opcodeBuffer, idBuffer, requestBuffer }); var tcs = new TaskCompletionSource <T>(); this.requestCallback[this.requestId] = (messageBytes, status) => { switch (status) { case RpcResponseStatus.Timeout: tcs.SetException(new Exception($"rpc timeout {opcode} {MongoHelper.ToJson(request)}")); return; case RpcResponseStatus.Exception: BinaryFormatter formatter = new BinaryFormatter(null, new StreamingContext(StreamingContextStates.All)); Exception exception; using (MemoryStream stream = new MemoryStream(messageBytes, 6, messageBytes.Length - 6)) { exception = (Exception)formatter.Deserialize(stream); } tcs.SetException(exception); return; } // RpcResponseStatus.Succee T response = MongoHelper.FromBson <T>(messageBytes, 6); tcs.SetResult(response); }; if (waitTime > 0) { this.service.Timer.Add(TimeHelper.Now() + waitTime, () => { this.RpcCallback(channel, this.requestId, null, RpcResponseStatus.Timeout); }); } return(tcs.Task); }
public object Clone() { return(MongoHelper.FromBson <Options>(MongoHelper.ToBson(this))); }
public byte[] SerializeToByteArray(object obj) { return(MongoHelper.ToBson(obj)); }