Beispiel #1
0
        public void Send(ushort opcode, object message)
        {
            if (this.IsDisposed)
            {
                throw new Exception("session已经被Dispose了");
            }

            this.LastSendTime = TimeHelper.Now();

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

            MemoryStream stream = this.Stream;

            stream.Seek(Packet.MessageIndex, SeekOrigin.Begin);
            stream.SetLength(Packet.MessageIndex);
            MessagePackHelper.SerializeTo(opcode, message, stream);
            stream.Seek(0, SeekOrigin.Begin);

            opcodeBytes.WriteTo(0, opcode);
            Array.Copy(opcodeBytes, 0, stream.GetBuffer(), 0, opcodeBytes.Length);

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

            object message;

            try
            {
                Type type = OpcodeTypeComponent.Instance.GetType(opcode);
                message = MessagePackHelper.DeserializeFrom(opcode, type, 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);
        }