Beispiel #1
0
        private void Run(MemoryStream memoryStream)
        {
            memoryStream.Seek(Packet.MessageIndex, SeekOrigin.Begin);
            ushort opcode = BitConverter.ToUInt16(memoryStream.GetBuffer(), Packet.OpcodeIndex);

            object message;

            try
            {
                OpcodeTypeComponent opcodeTypeComponent = this.Network.Entity.GetComponent <OpcodeTypeComponent>();
                object instance = opcodeTypeComponent.GetInstance(opcode);
                message = this.Network.MessagePacker.DeserializeFrom(instance, memoryStream);

                if (OpcodeHelper.IsNeedDebugLogMessage(opcode))
                {
                    Log.Msg(message);
                }
            }
            catch (Exception e)
            {
                // 出现任何消息解析异常都要断开Session,防止客户端伪造消息
                Log.Error($"opcode: {opcode} {this.Network.Count} {e}, ip: {this.RemoteAddress}");
                this.Error = ErrorCode.ERR_PacketParserError;
                this.Network.Remove(this.Id);
                return;
            }

            RunMessage(opcode, message);
        }
Beispiel #2
0
        public void Run(Session s, Packet p)
        {
            ushort opcode = p.Opcode();
            byte   flag   = p.Flag();

            OpcodeTypeComponent opcodeTypeComponent = Game.Scene.GetComponent <OpcodeTypeComponent>();
            Type   responseType = opcodeTypeComponent.GetType(opcode);
            object message      = ProtobufHelper.FromBytes(responseType, p.Bytes, Packet.Index, p.Length - Packet.Index);

            if ((flag & 0x01) > 0)
            {
                IResponse response = message as IResponse;
                if (response == null)
                {
                    throw new Exception($"flag is response, but hotfix message is not! {opcode}");
                }

                Action <IResponse> action;
                if (!this.requestCallback.TryGetValue(response.RpcId, out action))
                {
                    return;
                }
                this.requestCallback.Remove(response.RpcId);

                action(response);
                return;
            }

            Game.Scene.GetComponent <MessageDispatherComponent>().Handle(session, new MessageInfo(opcode, message));
        }
Beispiel #3
0
        public void Dispatch(Session session, Packet packet)
        {
            ushort opcode = packet.Opcode();

            if (OpcodeHelper.IsClientHotfixMessage(opcode))
            {
                session.GetComponent <SessionCallbackComponent>().MessageCallback.Invoke(session, packet);
                return;
            }

            OpcodeTypeComponent opcodeTypeComponent = session.Network.Entity.GetComponent <OpcodeTypeComponent>();
            Type   responseType = opcodeTypeComponent.GetType(opcode);
            object message      = session.Network.MessagePacker.DeserializeFrom(responseType, packet.Bytes, Packet.Index, packet.Length - Packet.Index);
            // 如果是帧同步消息,交给ClientFrameComponent处理
            FrameMessage frameMessage = message as FrameMessage;

            if (frameMessage != null)
            {
                Game.Scene.GetComponent <ClientFrameComponent>().Add(session, frameMessage);
                return;
            }

            // 普通消息或者是Rpc请求消息
            MessageInfo messageInfo = new MessageInfo(opcode, message);

            Game.Scene.GetComponent <MessageDispatherComponent>().Handle(session, messageInfo);
        }
Beispiel #4
0
        public Task <IResponse> Call(IRequest request)
        {
            uint rpcId = ++RpcId;
            var  tcs   = new TaskCompletionSource <IResponse>();

            OpcodeTypeComponent opcodeTypeComponent = this.Network.Entity.GetComponent <OpcodeTypeComponent>();
            ushort opcode = opcodeTypeComponent.GetOpcode(request.GetType());

            byte[] bytes = this.Network.MessagePacker.SerializeToByteArray(request);

            this.requestCallback[rpcId] = (packetInfo) =>
            {
                try
                {
                    Type      responseType = opcodeTypeComponent.GetType(packetInfo.Opcode);
                    object    message      = this.Network.MessagePacker.DeserializeFrom(responseType, packetInfo.Bytes, packetInfo.Index, packetInfo.Length);
                    IResponse response     = (IResponse)message;
                    if (response.Error > ErrorCode.ERR_Exception)
                    {
                        throw new RpcException(response.Error, response.Message);
                    }

                    tcs.SetResult(response);
                }
                catch (Exception e)
                {
                    tcs.SetException(new Exception($"Rpc Error: {packetInfo.Opcode}", e));
                }
            };

            const byte flag = 0x80;

            this.SendMessage(flag, opcode, rpcId, bytes);
            return(tcs.Task);
        }
Beispiel #5
0
        public void Send(byte flag, IMessage message)
        {
            OpcodeTypeComponent opcodeTypeComponent = this.Network.Entity.GetComponent <OpcodeTypeComponent>();
            ushort opcode = opcodeTypeComponent.GetOpcode(message.GetType());

            Send(flag, opcode, message);
        }
Beispiel #6
0
 public static void Register(this OpcodeTypeComponent self)
 {
     self.RegisterType(30, typeof(ActorResponse), () => { return(new ActorResponse()); });
     self.RegisterType(1, typeof(ResponseMessage), () => { return(new ResponseMessage()); });
     self.RegisterType(20, typeof(ObjectAddRequest), () => { return(new ObjectAddRequest()); });
     self.RegisterType(21, typeof(ObjectAddResponse), () => { return(new ObjectAddResponse()); });
     self.RegisterType(22, typeof(ObjectRemoveRequest), () => { return(new ObjectRemoveRequest()); });
     self.RegisterType(23, typeof(ObjectRemoveResponse), () => { return(new ObjectRemoveResponse()); });
     self.RegisterType(24, typeof(ObjectLockRequest), () => { return(new ObjectLockRequest()); });
     self.RegisterType(25, typeof(ObjectLockResponse), () => { return(new ObjectLockResponse()); });
     self.RegisterType(26, typeof(ObjectUnLockRequest), () => { return(new ObjectUnLockRequest()); });
     self.RegisterType(27, typeof(ObjectUnLockResponse), () => { return(new ObjectUnLockResponse()); });
     self.RegisterType(28, typeof(ObjectGetRequest), () => { return(new ObjectGetRequest()); });
     self.RegisterType(29, typeof(ObjectGetResponse), () => { return(new ObjectGetResponse()); });
     self.RegisterType(2, typeof(C2WEB_UserLogin), () => { return(new C2WEB_UserLogin()); });
     self.RegisterType(3, typeof(WEB2C_UserLogin), () => { return(new WEB2C_UserLogin()); });
     self.RegisterType(4, typeof(C2WEB_CreateRole), () => { return(new C2WEB_CreateRole()); });
     self.RegisterType(5, typeof(WEB2C_CreateRole), () => { return(new WEB2C_CreateRole()); });
     self.RegisterType(6, typeof(C2S_UserLogin), () => { return(new C2S_UserLogin()); });
     self.RegisterType(7, typeof(S2C_UserLogin), () => { return(new S2C_UserLogin()); });
     self.RegisterType(8, typeof(SaveRoleInfo), () => { return(new SaveRoleInfo()); });
     self.RegisterType(9, typeof(S2C_RoleInfo), () => { return(new S2C_RoleInfo()); });
     self.RegisterType(10, typeof(ServerHeart), () => { return(new ServerHeart()); });
     self.RegisterType(11, typeof(S2L_RegisterServer), () => { return(new S2L_RegisterServer()); });
     self.RegisterType(12, typeof(G2M_CreateUnit), () => { return(new G2M_CreateUnit()); });
     self.RegisterType(13, typeof(M2G_CreateUnit), () => { return(new M2G_CreateUnit()); });
     self.RegisterType(14, typeof(G2L_GetMapAddress), () => { return(new G2L_GetMapAddress()); });
     self.RegisterType(15, typeof(L2G_GetMapAddress), () => { return(new L2G_GetMapAddress()); });
     self.RegisterType(18, typeof(C2M_EnterRoom), () => { return(new C2M_EnterRoom()); });
     self.RegisterType(19, typeof(M2C_EnterRoom), () => { return(new M2C_EnterRoom()); });
     self.RegisterType(31, typeof(G2M_UnitDispose), () => { return(new G2M_UnitDispose()); });
 }
Beispiel #7
0
        public async Task <IResponse> Run()
        {
            Session             session             = Game.Scene.GetComponent <NetInnerComponent>().Get(this.proxy.Address);
            OpcodeTypeComponent opcodeTypeComponent = session.Network.Entity.GetComponent <OpcodeTypeComponent>();

            ushort opcode = opcodeTypeComponent.GetOpcode(message.GetType());

            byte[] requestBytes = session.Network.MessagePacker.SerializeToByteArray(message);

            ActorRequest actorRequest = new ActorRequest()
            {
                Id = this.proxy.Id, Op = opcode, AMessage = requestBytes
            };

            ActorResponse actorResponse = (ActorResponse)await session.Call(actorRequest, this.proxy.CancellationTokenSource.Token);

            if (actorResponse.Error != ErrorCode.ERR_NotFoundActor)
            {
                if (this.Tcs != null)
                {
                    Type      type     = opcodeTypeComponent.GetType(actorResponse.Op);
                    IResponse response = (IResponse)session.Network.MessagePacker.DeserializeFrom(type, actorResponse.AMessage);
                    this.Tcs?.SetResult(response);
                }
            }
            return(actorResponse);
        }
        public void Run(Session s, byte flag, ushort opcode, MemoryStream memoryStream)
        {
            OpcodeTypeComponent opcodeTypeComponent = Game.Scene.GetComponent <OpcodeTypeComponent>();
            object instance = opcodeTypeComponent.GetInstance(opcode);
            object message  = this.Network.MessagePacker.DeserializeFrom(instance, memoryStream);

            if (OpcodeHelper.IsNeedDebugLogMessage(opcode))
            {
                Log.Msg(message);
            }

            if ((flag & 0x01) > 0)
            {
                IResponse response = message as IResponse;
                if (response == null)
                {
                    throw new Exception($"flag is response, but hotfix message is not! {opcode}");
                }

                Action <IResponse> action;
                if (!this.requestCallback.TryGetValue(response.RpcId, out action))
                {
                    return;
                }
                this.requestCallback.Remove(response.RpcId);

                action(response);
                return;
            }

            Game.Scene.GetComponent <MessageDispatcherComponent>().Handle(s, new MessageInfo(opcode, message));
        }
Beispiel #9
0
        private void Run(MemoryStream memoryStream)
        {
            memoryStream.Seek(Packet.MessageIndex, SeekOrigin.Begin);
            byte   flag   = memoryStream.GetBuffer()[Packet.OpcodeIndex];
            ushort opcode = BitConverter.ToUInt16(memoryStream.GetBuffer(), Packet.OpcodeIndex);

// #if !SERVER
//          if (OpcodeHelper.IsClientHotfixMessage(opcode))
//          {
//              this.GetComponent<SessionCallbackComponent>().MessageCallback.Invoke(this, opcode, memoryStream);
//              return;
//          }
// #endif

            object message;

            try
            {
                OpcodeTypeComponent opcodeTypeComponent = this.Network.Entity.GetComponent <OpcodeTypeComponent>();
                object instance = opcodeTypeComponent.GetInstance(opcode);
                message = this.Network.MessagePacker.DeserializeFrom(instance, memoryStream);

                if (OpcodeHelper.IsNeedDebugLogMessage(opcode))
                {
                    Log.Msg(message);
                }
            }
            catch (Exception e)
            {
                // 出现任何消息解析异常都要断开Session,防止客户端伪造消息
                Log.Error($"opcode: {opcode} {this.Network.Count} {e}, ip: {this.RemoteAddress}");
                this.Error = ErrorCode.ERR_PacketParserError;
                this.Network.Remove(this.Id);
                return;
            }

            if (!(message is IResponse response))
            {
                this.Network.MessageDispatcher.Dispatch(this, opcode, message);
                return;
            }

            // flag第一位为1表示这是rpc返回消息,否则交由MessageDispatcher分发
            //if (flag == 109)
            //{
            //	this.Network.MessageDispatcher.Dispatch(this, opcode, message);
            //	return;
            //}

            Action <IResponse> action;

            if (!this.requestCallback.TryGetValue(response.RpcId, out action))
            {
                throw new Exception($"not found rpc, response message: {StringHelper.MessageToStr(response)}");
            }
            this.requestCallback.Remove(response.RpcId);

            action(response);
        }
Beispiel #10
0
        /// <summary>
        /// 读取消息
        /// </summary>
        /// <param name="memoryStream">包体数据</param>
        private void Run(MemoryStream memoryStream)
        {
            memoryStream.Seek(Packet.MessageIndex, SeekOrigin.Begin);
            //读取操作码 操作码也是属于包体的一部分
            ushort opcode = BitConverter.ToUInt16(memoryStream.GetBuffer(), Packet.OpcodeIndex);

#if !SERVER
            //如果是热更模块的操作码 >10000以上的
            if (OpcodeHelper.IsClientHotfixMessage(opcode))
            {
                //提交到热更层Session对象,在其内部注册的方法去处理
                this.GetComponent <SessionCallbackComponent>().MessageCallback.Invoke(this, opcode, memoryStream);
                return;
            }
#endif

            object message;
            try
            {
                //通过操作码 获取到实例
                OpcodeTypeComponent opcodeTypeComponent = this.Network.Entity.GetComponent <OpcodeTypeComponent>();
                object instance = opcodeTypeComponent.GetInstance(opcode);
                //反序列化 将内存流剩下的数据反序列化成proto实体
                message = this.Network.MessagePacker.DeserializeFrom(instance, memoryStream);

                //需要调试日志的信息 就打印出来
                if (OpcodeHelper.IsNeedDebugLogMessage(opcode))
                {
                    Log.Msg(message);
                }
            }
            catch (Exception e)
            {
                // 出现任何消息解析异常都要断开Session,防止客户端伪造消息
                Log.Error($"opcode: {opcode} {this.Network.Count} {e}, ip: {this.RemoteAddress}");
                this.Error = ErrorCode.ERR_PacketParserError;
                this.Network.Remove(this.Id);
                return;
            }

            //如果消息不是响应类型的消息 进行派发处理
            if (!(message is IResponse response))
            {
                //进行派发处理
                this.Network.MessageDispatcher.Dispatch(this, opcode, message);
                return;
            }

            //如果是响应类型的消息
            //从requestCallback缓存取出要执行的方法 将message压入到方法中 然后执行该方法 这涉及到ETTask的封装 等待了解
            Action <IResponse> action;
            if (!this.requestCallback.TryGetValue(response.RpcId, out action))
            {
                throw new Exception($"not found rpc, response message: {StringHelper.MessageToStr(response)}");
            }
            this.requestCallback.Remove(response.RpcId);

            action(response);
        }
Beispiel #11
0
        private void Run(Packet packet)
        {
            packet.Flag   = packet.Bytes[Packet.FlagIndex];
            packet.Opcode = BitConverter.ToUInt16(packet.Bytes, Packet.OpcodeIndex);
            packet.Stream.Seek(Packet.MessageIndex, SeekOrigin.Begin);

            byte   flag   = packet.Flag;
            ushort opcode = packet.Opcode;

#if !SERVER
            /*if (OpcodeHelper.IsClientHotfixMessage(opcode))
             * {
             *      this.Network.MessageDispatcher.Dispatch(this, packet);
             *      return;
             * }*/
#endif
            Log.Info(flag.ToHex());
            // flag第一位为1表示这是rpc返回消息,否则交由MessageDispatcher分发
            if ((flag & 0x01) == 0)
            {
                this.Network.MessageDispatcher.Dispatch(this, packet);
                return;
            }

            object message;
            try
            {
                OpcodeTypeComponent opcodeTypeComponent = this.Network.Entity.GetComponent <OpcodeTypeComponent>();
                object instance = opcodeTypeComponent.GetInstance(opcode);
                Log.Info(opcode.ToString());
                message = this.Network.MessagePacker.DeserializeFrom(instance, packet.Stream);
                //Log.Debug($"recv: {JsonHelper.ToJson(message)}");
            }
            catch (Exception e)
            {
                // 出现任何消息解析异常都要断开Session,防止客户端伪造消息
                Log.Error($"opcode: {opcode} {this.Network.Count} {e} ");
                this.Error = ErrorCode.ERR_PacketParserError;
                this.Network.Remove(this.Id);
                return;
            }

            IResponse response = message as IResponse;
            mLatencyComponent.AddAMsgLan(TimeHelper.GetCurrentTimeUnix() - response.Time);


            if (response == null)
            {
                throw new Exception($"flag is response, but message is not! {opcode}");
            }
            Action <IResponse> action;
            if (!this.requestCallback.TryGetValue(response.RpcId, out action))
            {
                return;
            }
            this.requestCallback.Remove(response.RpcId);

            action(response);
        }
Beispiel #12
0
        public void Send(IMessage message)
        {
            OpcodeTypeComponent opcodeTypeComponent = Game.Scene.GetComponent <OpcodeTypeComponent>();
            ushort opcode = opcodeTypeComponent.GetOpcode(message.GetType());

            byte[] bytes = this.Network.MessagePacker.SerializeToByteArray(message);
            this.Send(opcode, bytes);
        }
Beispiel #13
0
        /// <summary>
        /// 发送逻辑1-取到协议的操作码
        /// </summary>
        /// <param name="message"></param>
        public void Send(IMessage message)
        {
            OpcodeTypeComponent opcodeTypeComponent = this.Network.Entity.GetComponent <OpcodeTypeComponent>();
            //获取到协议号(操作码)
            ushort opcode = opcodeTypeComponent.GetOpcode(message.GetType());

            Send(opcode, message);
        }
Beispiel #14
0
        private void Run(MemoryStream memoryStream)
        {
            memoryStream.Seek(Packet.MessageIndex, SeekOrigin.Begin);
            byte   flag   = memoryStream.GetBuffer()[Packet.FlagIndex];
            ushort opcode = BitConverter.ToUInt16(memoryStream.GetBuffer(), Packet.OpcodeIndex);

#if !SERVER
            if (OpcodeHelper.IsClientHotfixMessage(opcode))
            {
                this.GetComponent <SessionCallbackComponent>().MessageCallback.Invoke(this, flag, opcode, memoryStream);
                return;
            }
#endif

            object message;
            try
            {
                OpcodeTypeComponent opcodeTypeComponent = this.Network.Entity.GetComponent <OpcodeTypeComponent>();
                object instance = opcodeTypeComponent.GetInstance(opcode);
                message = this.Network.MessagePacker.DeserializeFrom(instance, memoryStream);
                //Log.Debug($"recv: {JsonHelper.ToJson(message)}");

                if (OpcodeHelper.IsNeedDebugLogMessage(opcode))
                {
                    Log.Msg(message);
                }
            }
            catch (Exception e)
            {
                // 出现任何消息解析异常都要断开Session,防止客户端伪造消息
                Log.Error($"opcode: {opcode} {this.Network.Count} {e} ");
                this.Error = ErrorCode.ERR_PacketParserError;
                this.Network.Remove(this.Id);
                return;
            }

            // flag第一位为1表示这是rpc返回消息,否则交由MessageDispatcher分发
            if ((flag & 0x01) == 0)
            {
                this.Network.MessageDispatcher.Dispatch(this, opcode, message);
                return;
            }

            IResponse response = message as IResponse;
            if (response == null)
            {
                throw new Exception($"flag is response, but message is not! {opcode}");
            }
            Action <IResponse> action;
            if (!this.requestCallback.TryGetValue(response.RpcId, out action))
            {
                return;
            }
            this.requestCallback.Remove(response.RpcId);

            action(response);
        }
Beispiel #15
0
        public void Send(byte flag, IMessage message)
        {
            OpcodeTypeComponent opcodeTypeComponent = this.Network.Entity.GetComponent <OpcodeTypeComponent>();
            ushort opcode = opcodeTypeComponent.GetOpcode(message.GetType());

            byte[] bytes = this.Network.MessagePacker.SerializeToByteArray(message);

            Send(flag, opcode, bytes);
        }
Beispiel #16
0
        /// <summary>
        /// 处理收到的网络消息
        /// </summary>
        /// <param name="packet">Packet.</param>
        private void Run(MemoryStream memoryStream)
        {
            memoryStream.Seek(Packet.MessageIndex, SeekOrigin.Begin);
            byte flag = memoryStream.GetBuffer()[Packet.FlagIndex];
            //得到操作码
            ushort opcode = BitConverter.ToUInt16(memoryStream.GetBuffer(), Packet.OpcodeIndex);

#if !SERVER
            //如果是客户端  如果是热更新的操作码 就直接把收到的消息派发处理
            if (OpcodeHelper.IsClientHotfixMessage(opcode))
            {
                this.GetComponent <SessionCallbackComponent>().MessageCallback.Invoke(this, flag, opcode, memoryStream);
                return;
            }
#endif

            object message;
            try
            {
                OpcodeTypeComponent opcodeTypeComponent = this.Network.Entity.GetComponent <OpcodeTypeComponent>(); //操作码和类的映射关系
                object instance = opcodeTypeComponent.GetInstance(opcode);                                          //根据操作码得到类
                message = this.Network.MessagePacker.DeserializeFrom(instance, memoryStream);                       //将包里面的数据根据操作码找到的类型反序列化为object
                                                                                                                    //Log.Debug($"recv: {JsonHelper.ToJson(message)}");
            }
            catch (Exception e)
            {
                // 出现任何消息解析异常都要断开Session,防止客户端伪造消息
                Log.Error($"opcode: {opcode} {this.Network.Count} {e} ");
                this.Error = ErrorCode.ERR_PacketParserError;
                this.Network.Remove(this.Id);
                return;
            }

            // flag第一位为1表示这是rpc返回消息  如果是0 说明这个只是普通的消息 由MessageDispatcher处理
            if ((flag & 0x01) == 0)
            {
                this.Network.MessageDispatcher.Dispatch(this, opcode, message);
                return;
            }
            //是RPC消息  把消息体转换为	IResponse 类型
            IResponse response = message as IResponse;
            if (response == null)             //做验证保护
            {
                throw new Exception($"flag is response, but message is not! {opcode}");
            }
            Action <IResponse> action;              //如果回来的是RPC消息  查看RPC消息列表
            if (!this.requestCallback.TryGetValue(response.RpcId, out action))
            {
                return;                                  //没有就滚蛋
            }
            this.requestCallback.Remove(response.RpcId); //从字典中移除这个RPC消息

            action(response);                            //处理这个消息 RPC消息
        }
Beispiel #17
0
        private void Run(Packet packet)
        {
            byte   flag   = packet.Flag;
            ushort opcode = packet.Opcode;

#if !SERVER
            if (OpcodeHelper.IsClientHotfixMessage(opcode))
            {
                this.Network.MessageDispatcher.Dispatch(this, packet);
                return;
            }
#endif

            // flag第一位为1表示这是rpc返回消息,否则交由MessageDispatcher分发
            if ((flag & 0x01) == 0)
            {
                this.Network.MessageDispatcher.Dispatch(this, packet);
                return;
            }

            IMessage message;
            try
            {
                OpcodeTypeComponent opcodeTypeComponent = this.Network.Entity.GetComponent <OpcodeTypeComponent>();
                Log.Debug("opcode:" + opcode);
                message = opcodeTypeComponent.GetNewMessage(opcode);
                message.MergeFrom(packet.Bytes, packet.Offset, packet.Length);
                //Log.Debug($"recv: {JsonHelper.ToJson(message)}");
            }
            catch (Exception e)
            {
                // 出现任何消息解析异常都要断开Session,防止客户端伪造消息
                Log.Error(e);
                this.Error = ErrorCode.ERR_PacketParserError;
                this.Network.Remove(this.Id);
                return;
            }

            IResponse response = message as IResponse;
            if (response == null)
            {
                throw new Exception($"flag is response, but message is not! {opcode}");
            }
            Action <IResponse> action;
            if (!this.requestCallback.TryGetValue(response.RpcId, out action))
            {
                return;
            }
            this.requestCallback.Remove(response.RpcId);

            action(response);
        }
Beispiel #18
0
        public void Reply(uint rpcId, IResponse message)
        {
            if (this.IsDisposed)
            {
                throw new Exception("session已经被Dispose了");
            }
            OpcodeTypeComponent opcodeTypeComponent = Game.Scene.GetComponent <OpcodeTypeComponent>();
            ushort opcode = opcodeTypeComponent.GetOpcode(message.GetType());

            byte[]     bytes = this.Network.MessagePacker.SerializeToByteArray(message);
            const byte flag  = 0x40;

            this.SendMessage(flag, opcode, rpcId, bytes);
        }
        public async Task Handle(Session session, Entity entity, ActorRequest actorRequest, object message)
        {
            try
            {
                Request request = message as Request;
                if (request == null)
                {
                    Log.Error($"消息类型转换错误: {message.GetType().FullName} to {typeof (Request).Name}");
                    return;
                }
                E e = entity as E;
                if (e == null)
                {
                    Log.Error($"Actor类型转换错误: {entity.GetType().Name} to {typeof(E).Name}");
                    return;
                }

                int rpcId = request.RpcId;
                await this.Run(e, request, response =>
                {
                    // 等回调回来,session可以已经断开了,所以需要判断session id是否为0
                    if (session.IsDisposed)
                    {
                        return;
                    }

                    response.RpcId = rpcId;

                    OpcodeTypeComponent opcodeTypeComponent = session.Network.Entity.GetComponent <OpcodeTypeComponent>();
                    ushort opcode         = opcodeTypeComponent.GetOpcode(response.GetType());
                    byte[] repsponseBytes = session.Network.MessagePacker.SerializeToByteArray(response);

                    ActorResponse actorResponse = new ActorResponse
                    {
                        Flag     = 0x01,
                        Op       = opcode,
                        AMessage = repsponseBytes
                    };
                    actorResponse.RpcId = actorRequest.RpcId;
                    session.Reply(actorResponse);
                });
            }
            catch (Exception e)
            {
                throw new Exception($"解释消息失败: {message.GetType().FullName}", e);
            }
        }
Beispiel #20
0
        private void Run(Packet packet)
        {
            if (packet.Length < Packet.MinSize)
            {
                Log.Error($"message error length < {Packet.MinSize}, ip: {this.RemoteAddress}");
                this.Network.Remove(this.Id);
                return;
            }

            byte   flag   = packet.Flag;
            ushort opcode = packet.Opcode;

#if !SERVER
            if (OpcodeHelper.IsClientHotfixMessage(opcode))
            {
                this.Network.MessageDispatcher.Dispatch(this, packet);
                return;
            }
#endif

            // flag第一位为1表示这是rpc返回消息,否则交由MessageDispatcher分发
            if ((flag & 0x01) == 0)
            {
                this.Network.MessageDispatcher.Dispatch(this, packet);
                return;
            }

            OpcodeTypeComponent opcodeTypeComponent = this.Network.Entity.GetComponent <OpcodeTypeComponent>();
            Type   responseType = opcodeTypeComponent.GetType(opcode);
            object message      = this.Network.MessagePacker.DeserializeFrom(responseType, packet.Bytes, Packet.Index, packet.Length - Packet.Index);
            //Log.Debug($"recv: {JsonHelper.ToJson(message)}");

            IResponse response = message as IResponse;
            if (response == null)
            {
                throw new Exception($"flag is response, but message is not! {opcode}");
            }
            Action <IResponse> action;
            if (!this.requestCallback.TryGetValue(response.RpcId, out action))
            {
                return;
            }
            this.requestCallback.Remove(response.RpcId);

            action(response);
        }
        public void Load()
        {
            this.handlers.Clear();

            ETModel.MessageDispatherComponent messageDispatherComponent = ETModel.Game.Scene.GetComponent <ETModel.MessageDispatherComponent>();
            ETModel.OpcodeTypeComponent       opcodeTypeComponent       = ETModel.Game.Scene.GetComponent <ETModel.OpcodeTypeComponent>();

            Type[] types = ETModel.Game.Hotfix.GetHotfixTypes();

            foreach (Type type in types)
            {
                object[] attrs = type.GetCustomAttributes(typeof(MessageHandlerAttribute), false);
                if (attrs.Length == 0)
                {
                    continue;
                }

                IMHandler iMHandler = Activator.CreateInstance(type) as IMHandler;
                if (iMHandler == null)
                {
                    Log.Error($"message handle {type.Name} 需要继承 IMHandler");
                    continue;
                }

                Type   messageType = iMHandler.GetMessageType();
                ushort opcode      = this.Entity.GetComponent <OpcodeTypeComponent>().GetOpcode(messageType);
                if (opcode != 0)
                {
                    this.RegisterHandler(opcode, iMHandler);
                }

                // 尝试注册到mono层
                if (messageDispatherComponent != null && opcodeTypeComponent != null)
                {
                    ushort monoOpcode = opcodeTypeComponent.GetOpcode(messageType);
                    if (monoOpcode == 0)
                    {
                        continue;
                    }

                    MessageProxy messageProxy = new MessageProxy(messageType, (session, o) => { iMHandler.Handle(session, o); });
                    messageDispatherComponent.RegisterHandler(monoOpcode, messageProxy);
                }
            }
        }
Beispiel #22
0
        public void Dispatch(Session session, Packet packet)
        {
            object message;

            try
            {
                if (OpcodeHelper.IsClientHotfixMessage(packet.Opcode))
                {
                    session.GetComponent <SessionCallbackComponent>().MessageCallback.Invoke(session, packet);
                    return;
                }

                OpcodeTypeComponent opcodeTypeComponent = session.Network.Entity.GetComponent <OpcodeTypeComponent>();
                Type responseType = opcodeTypeComponent.GetType(packet.Opcode);
                message = session.Network.MessagePacker.DeserializeFrom(responseType, packet.Stream);
            }
            catch (Exception e)
            {
                // 出现任何解析消息异常都要断开Session,防止客户端伪造消息
                Log.Error(e);
                session.Error = ErrorCode.ERR_PacketParserError;
                session.Network.Remove(session.Id);
                return;
            }


            // 如果是帧同步消息,交给ClientFrameComponent处理
            FrameMessage frameMessage = message as FrameMessage;

            if (frameMessage != null)
            {
                Game.Scene.GetComponent <ClientFrameComponent>().Add(session, frameMessage);
                return;
            }

            // 普通消息或者是Rpc请求消息

            MessageInfo messageInfo = new MessageInfo(packet.Opcode, message);

            Game.Scene.GetComponent <MessageDispatherComponent>().Handle(session, messageInfo);
        }
Beispiel #23
0
        private void UpdateFrame()
        {
            if (this.Queue.Count == 0)
            {
                return;
            }
            SessionFrameMessage sessionFrameMessage = this.Queue.Dequeue();

            this.Frame = sessionFrameMessage.FrameMessage.Frame;

            for (int i = 0; i < sessionFrameMessage.FrameMessage.Messages.Count; ++i)
            {
                OneFrameMessage oneFrameMessage = sessionFrameMessage.FrameMessage.Messages[i];

                Session             session             = sessionFrameMessage.Session;
                OpcodeTypeComponent opcodeTypeComponent = session.Network.Entity.GetComponent <OpcodeTypeComponent>();
                Type type = opcodeTypeComponent.GetType(oneFrameMessage.Op);

                IMessage message = (IMessage)session.Network.MessagePacker.DeserializeFrom(type, oneFrameMessage.AMessage);
                Game.Scene.GetComponent <MessageDispatherComponent>().Handle(sessionFrameMessage.Session, new MessageInfo(oneFrameMessage.Op, message));
            }
        }
Beispiel #24
0
        public void Update()
        {
            if (this.Queue.Count == 0)
            {
                return;
            }
            SessionFrameMessage sessionFrameMessage = this.Queue.Dequeue();

            this.Frame = sessionFrameMessage.FrameMessage.Frame;
            for (int i = 0; i < sessionFrameMessage.FrameMessage.Message.Count; ++i)
            {
                OneFrameMessage oneFrameMessage = sessionFrameMessage.FrameMessage.Message[i];

                Session             session             = sessionFrameMessage.Session;
                OpcodeTypeComponent opcodeTypeComponent = session.Network.Entity.GetComponent <OpcodeTypeComponent>();
                ushort opcode   = (ushort)oneFrameMessage.Op;
                object instance = opcodeTypeComponent.GetInstance(opcode);

                byte[]           bytes   = ByteString.Unsafe.GetBuffer(oneFrameMessage.AMessage);
                ETModel.IMessage message = (ETModel.IMessage)session.Network.MessagePacker.DeserializeFrom(instance, bytes, 0, bytes.Length);
                Game.Scene.GetComponent <MessageDispatherComponent>().Handle(sessionFrameMessage.Session, new MessageInfo((ushort)oneFrameMessage.Op, message));
            }
        }
Beispiel #25
0
        //------------//[MyAppend end]------------

        private void Run(MemoryStream memoryStream)
        {
            memoryStream.Seek(Packet.MessageIndex, SeekOrigin.Begin);
            ushort opcode = BitConverter.ToUInt16(memoryStream.GetBuffer(), Packet.OpcodeIndex);

            //------------//[MyAppend begin]------------
            if (!checkOpcode(opcode))
            {
                myDebug(opcode);
                this.Error = ErrorCode.ERR_PacketParserError;
                this.Network.Remove(this.Id);
                return;
            }
            //------------//[MyAppend end]------------

#if !SERVER
            if (OpcodeHelper.IsClientHotfixMessage(opcode))
            {
                this.GetComponent <SessionCallbackComponent>().MessageCallback.Invoke(this, opcode, memoryStream);
                return;
            }
#endif

            object message;
            try
            {
                OpcodeTypeComponent opcodeTypeComponent = this.Network.Entity.GetComponent <OpcodeTypeComponent>();
                object instance = opcodeTypeComponent.GetInstance(opcode);
                message = this.Network.MessagePacker.DeserializeFrom(instance, memoryStream);
            }
            catch (Exception e)
            {
                // 出现任何消息解析异常都要断开Session,防止客户端伪造消息
                //                Log.Error($"opcode: {opcode} {this.Network.Count} {e} " + myDebug(memoryStream));
                //Log.Error(e + ", opcode: " + opcode + ", this.Network.Count: " + this.Network.Count + ", " + myDebug(memoryStream));
                this.Error = ErrorCode.ERR_PacketParserError;
                this.Network.Remove(this.Id);
                return;
            }

            IResponse response = message as IResponse;
            if (response == null)
            {
                //屏蔽心跳日志输出 10008
                //屏蔽广播玩家下注日志 10050
                //屏蔽广播推送的消息 request
                //1011数据存储
                if (OpcodeHelper.IsNeedDebugLogMessage(opcode) &&
                    opcode != 10008 &&
                    opcode != 10050 &&
                    opcode != 1011 &&
                    opcode != 1012 &&
                    opcode != 1009 &&
                    opcode != 1010 &&
                    (message as IActorMessage) == null
                    )
                {
                    Log.Msg(message);
                }
                this.Network.MessageDispatcher.Dispatch(this, opcode, message);
                return;
            }

            Action <IResponse> action;
            if (!this.requestCallback.TryGetValue(response.RpcId, out action))
            {
                throw new Exception($"not found rpc, response message: {StringHelper.MessageToStr(response)}");
            }
            this.requestCallback.Remove(response.RpcId);

            action(response);

            //屏蔽心跳日志输出 10008
            //屏蔽广播玩家下注日志 10050
            if (OpcodeHelper.IsNeedDebugLogMessage(opcode) && opcode != 10008 && opcode != 10050 && opcode != 1011 && opcode != 1012 && opcode != 1010 && opcode != 1009)
            {
                Log.Msg(message);
            }
        }