Пример #1
0
        private void EndReceive(SocketAsyncEventArgs pArguments)
        {
            if (mDisconnected != 0) return;
            if (pArguments.BytesTransferred <= 0)
            {
                if (pArguments.SocketError != SocketError.Success && pArguments.SocketError != SocketError.ConnectionReset) Log.WriteLine(ELogLevel.Error, "[{0}] Receive Error: {1}", Host, pArguments.SocketError);
                Disconnect();
                return;
            }
            mReceiveLength += pArguments.BytesTransferred;

            while (mReceiveLength > 4)
            {
                if (mReceivingPacketLength == 0)
                {
                    if (!mReceiveCrypto.ConfirmHeader(mReceiveBuffer, mReceiveStart))
                    {
                        Log.WriteLine(ELogLevel.Error, "[{0}] Invalid Packet Header", Host);
                        Disconnect();
                        return;
                    }
                    mReceivingPacketLength = mReceiveCrypto.GetHeaderLength(mReceiveBuffer, mReceiveStart);
                }
                if (mReceivingPacketLength > 0 && mReceiveLength >= mReceivingPacketLength + 4)
                {
                    mReceiveCrypto.Decrypt(mReceiveBuffer, mReceiveStart + 4, mReceivingPacketLength);

                    Packet packet = new Packet(mReceiveBuffer, mReceiveStart + 4, mReceivingPacketLength);
                    PacketHandlerAttribute handler = sHandlers.GetOrDefault(packet.Opcode, null);
                    if (handler != null) Server.AddCallback(() => handler.Processor(this, packet));
                    else
                    {
                        Log.WriteLine(ELogLevel.Debug, "[{0}] Receiving 0x{1}, {2} Bytes", Host, ((ushort)packet.Opcode).ToString("X4"), packet.Length);
                        packet.Dump();
                    }

                    mReceiveStart += mReceivingPacketLength + 4;
                    mReceiveLength -= mReceivingPacketLength + 4;
                    mReceivingPacketLength = 0;
                    mReceiveLast = DateTime.Now;
                }
            }

            if (mReceiveLength == 0) mReceiveStart = 0;
            else if (mReceiveStart > 0 && (mReceiveStart + mReceiveLength) >= mReceiveBuffer.Length)
            {
                Buffer.BlockCopy(mReceiveBuffer, mReceiveStart, mReceiveBuffer, 0, mReceiveLength);
                mReceiveStart = 0;
            }
            if (mReceiveLength == mReceiveBuffer.Length)
            {
                Log.WriteLine(ELogLevel.Error, "[{0}] Receive Overflow", Host);
                Disconnect();
            }
            else BeginReceive();
        }