using Fleck; namespace BattleServer { /// /// 客户端链接对象 /// class Client { private IWebSocketConnection socket; public Client(IWebSocketConnection _socket) { socket = _socket; socket.OnBinary = doBinary; socket.OnClose = close; } private void close (){ Service.Instance.Shutdown(this); } /// /// 接收rpc数据 /// /// private void doBinary(byte[] message) { BattleRpcMessage msg = ProtoDeSerialize(message); // Pb.BattleRpcMessage msg = Deserialize(message); Task.Run(() =>{ handle(msg); }); } /// /// 处理远程请求 /// /// private void handle(BattleRpcMessage msg) { try{ Console.WriteLine("收到战斗消息:{0}", msg.method); switch(msg.method){ case "Check": BattleReport report = ProtoDeSerialize(msg.data.value); bool ischeck = HotUpdateScripts.FightRunnerMgr.Instance.VerifyOnceFight(report); Console.WriteLine("战斗校验结果:{0}", ischeck); msg.data = new Google.Protobuf.WellKnownTypes.Any { type_url = "type.googleapis.com/BattleCheckResults", value = ProtoSerialize(new BattleCheckResults{ischeck=ischeck}), }; socket.Send(ProtoSerialize(msg)); break; } } catch (IOException ex){ Console.WriteLine("战斗异常 {0}",ex.Message); socket.Close(); } } /// /// 序列化并返回二进制 /// Serialize an Object and return byte[] /// /// /// public static byte[] ProtoSerialize(T obj) where T : class { using (var stream = new MemoryStream()) { ProtoBuf.Serializer.Serialize(stream, obj); return stream.ToArray(); } } /// /// 通过二进制反序列化 /// Deserialize with byte[] /// /// /// /// public static T ProtoDeSerialize(byte[] msg) where T : class { msg = msg == null ? new byte[]{} : msg; using (var ms = new MemoryStream(msg)) { var data = ProtoBuf.Serializer.Deserialize(ms); return data; } } } }