ReadByte() 공개 메소드

public ReadByte ( ) : int
리턴 int
예제 #1
0
        /// <summary>
        /// Creates a new <see cref="ChatRoom"/> from a received <see cref="ByteStream"/>
        /// </summary>
        public ChatRoom(ByteStream stream)
        {
            exchangeNumber = stream.ReadUshort();
            fullName       = stream.ReadString(stream.ReadByte(), Encoding.ASCII);
            instance       = stream.ReadUshort();

            // A small chat room info block will only contain the bare essentials:
            // exchange number, chat room name, and instance number.
            // The chat room class really wants a display name, so parse one here.
            if (stream.HasMoreData)
            {
                detailLevel = stream.ReadByte();
                unknownCode = stream.ReadUshort(); // No idea what this is

                using (TlvBlock block = new TlvBlock(stream.ReadByteArrayToEnd()))
                {
                    flags = block.ReadUshort(CHATROOM_FLAGS);
                    if (block.HasTlv(CHATROOM_CREATION_TIME))
                    {
                        creationTime = block.ReadDateTime(CHATROOM_CREATION_TIME);
                    }
                    maxMessageLength    = block.ReadUshort(CHATROOM_MESSAGE_LENGTH);
                    maxOccupants        = block.ReadUshort(CHATROOM_MAX_OCCUPANTS);
                    displayName         = block.ReadString(CHATROOM_DISPLAYNAME, Encoding.ASCII);
                    creationPermissions = block.ReadByte(CHATROOM_PERMISSIONS);

                    string charset = block.ReadString(CHATROOM_CHARSET1, Encoding.ASCII);
                    if (!String.IsNullOrEmpty(charset))
                    {
                        charSet1 = Encoding.GetEncoding(charset);
                    }
                    language1 = block.ReadString(CHATROOM_LANGUAGE1, Encoding.ASCII);

                    charset = block.ReadString(CHATROOM_CHARSET2, Encoding.ASCII);
                    if (!String.IsNullOrEmpty(charset))
                    {
                        charSet2 = Encoding.GetEncoding(charset);
                    }
                    language2 = block.ReadString(CHATROOM_LANGUAGE2, Encoding.ASCII);

                    contentType = block.ReadString(CHATROOM_CONTENTTYPE, Encoding.ASCII);
                }
            }

            // Make sure there's a display name to show
            if (String.IsNullOrEmpty(displayName))
            {
                Match match = AolUriParser.Match(fullName);
                if (match.Success)
                {
                    //displayName = UtilityMethods.DeHexUri(match.Groups["roomname"].Value);
                    int lastDashBeforeName = fullName.IndexOf('-', 16);
                    displayName = fullName.Substring(lastDashBeforeName + 1);
                }
                else
                {
                    displayName = fullName;
                }
            }
        }
예제 #2
0
        public FrameBlock[] ParseChunk(ByteStream chunk, ushort remoteSsrcId)
        {
            byte numBlocks = chunk.Data[0];

            // ks 7/18/11 - This seems like an odd place to do it, but I can't think of a better one.
            _videoQualityController.LogReceivedVideoQuality(remoteSsrcId, (VideoQuality)chunk.Data[1], (VideoQuality)chunk.Data[2]);

            byte jpegQuality = chunk.Data[3];

            Debug.Assert(jpegQuality > 0 && jpegQuality <= 100);

            chunk.CurrentOffset = ChunkHeaderLength;
            var blocks = new FrameBlock[numBlocks];

            for (int i = 0; i < numBlocks; i++)
            {
                var block = _frameBlockPool.GetNext();
                block.JpegQuality = jpegQuality;
                block.BlockX      = chunk.ReadByte();
                block.BlockY      = chunk.ReadByte();
                block.BlockType   = (BlockType)chunk.ReadByte();
                short payloadLength = chunk.ReadInt16();
                Debug.Assert(payloadLength > 0, "The payloadLength must be greater than 0");
                block.EncodedStream  = new MemoryStream(chunk.Data, chunk.CurrentOffset, payloadLength);
                chunk.CurrentOffset += payloadLength;
                blocks[i]            = block;
            }
            return(blocks);
        }
예제 #3
0
        private void ProcessShortUserInfoResponse(DataPacket dp, ByteStream data)
        {
            ushort length;

            ShortUserInfo ui = new ShortUserInfo();

            ui.Screenname = parent.RetrieveRequestID(dp.SNAC.RequestID) as string;

            Byte success = data.ReadByte();     // 0x0a

            length      = data.ReadUshortLE();
            ui.Nickname = data.ReadString(length, Encoding.ASCII);

            length       = data.ReadUshortLE();
            ui.Firstname = data.ReadString(length, Encoding.ASCII);

            length      = data.ReadUshortLE();
            ui.Lastname = data.ReadString(length, Encoding.ASCII);

            length   = data.ReadUshortLE();
            ui.Email = data.ReadString(length, Encoding.ASCII);

            Byte authflag = data.ReadByte();
            Byte unknown  = data.ReadByte();
            Byte gender   = data.ReadByte();

            if (ShortUserInfoReceived != null)
            {
                ShortUserInfoReceived(this, ui);
            }
        }
예제 #4
0
        /// <summary>
        /// Initializes a new BartID from a byte stream
        /// </summary>
        internal BartID(ByteStream stream)
        {
            type  = (BartTypeId)stream.ReadUshort();
            flags = (BartFlags)stream.ReadByte();
            byte dataLength = stream.ReadByte();

            data = stream.ReadByteArray(dataLength);
        }
예제 #5
0
        static public List <LogicRun.ModeObject> BytesToCode(byte[] code)
        {
            List <LogicRun.ModeObject> objs = new List <LogicRun.ModeObject>();
            ByteStream bdata  = new ByteStream(code);
            ByteStream bpos   = new ByteStream(code);
            int        count  = bdata.ReadWord();
            int        offset = bdata.ReadByte();

            bdata.offset(count * 2 + offset);
            bpos.offset(3 + offset);
            offset = 3 + offset + count * 2;
            int len;

            for (int i = 0; i < count; i++)
            {
                bdata.offset(bpos.ReadWord(), offset);
                switch ((CodeBinData)bdata.ReadByte())
                {
                case CodeBinData.OUTSIG:
                    len = bdata.ReadByte();
                    objs.Add(new LogicRun.SetOutput(bdata.ReadBuff((len + 7) / 8), len));
                    break;

                case CodeBinData.INPUTSIG:
                    len = bdata.ReadByte();
                    objs.Add(new LogicRun.CheckInput(bdata.ReadBuff((len + 7) / 8), bdata.ReadBuff((len + 7) / 8), len));
                    break;

                case CodeBinData.DELAY:
                    objs.Add(new LogicRun.Delay(bdata.ReadWord()));
                    break;

                case CodeBinData.PWMCONFIG:
                    objs.Add(new LogicRun.SetSpeed(bdata.ReadWord(), bdata.ReadWord(), bdata.ReadDWorde()));
                    break;

                case CodeBinData.PWMOUT:
                    len = bdata.ReadByte();
                    int[] pls = new int[len];
                    for (int j = 0; j < len; j++)
                    {
                        pls[j] = bdata.ReadDWorde();
                    }
                    objs.Add(new LogicRun.PWMRun(len, pls));
                    break;

                case CodeBinData.PWMSTOP: break;

                case CodeBinData.PLCCODE:
                    len = bdata.ReadWord();
                    objs.Add(new LogicRun.PLCCode(bdata.ReadBuff(len)));
                    break;
                }
            }
            return(objs);
        }
예제 #6
0
        override public List <Door> GetDoors()
        {
            List <Door> DoorList = new List <Door>();

            List <byte[]> SpawnDoorPacket = GetPacketsOfType("OP_SpawnDoor", PacketDirection.ServerToClient);

            if ((SpawnDoorPacket.Count == 0) || (SpawnDoorPacket[0].Length == 0))
            {
                return(DoorList);
            }

            int DoorCount = SpawnDoorPacket[0].Length / 100;

            ByteStream Buffer = new ByteStream(SpawnDoorPacket[0]);

            for (int d = 0; d < DoorCount; ++d)
            {
                string DoorName = Buffer.ReadFixedLengthString(32, false);

                float YPos = Buffer.ReadSingle();

                float XPos = Buffer.ReadSingle();

                float ZPos = Buffer.ReadSingle();

                float Heading = Buffer.ReadSingle();

                UInt32 Incline = Buffer.ReadUInt32();

                Int32 Size = Buffer.ReadInt32();

                Buffer.SkipBytes(4); // Skip Unknown

                Byte DoorID = Buffer.ReadByte();

                Byte OpenType = Buffer.ReadByte();

                Byte StateAtSpawn = Buffer.ReadByte();

                Byte InvertState = Buffer.ReadByte();

                Int32 DoorParam = Buffer.ReadInt32();

                // Skip past the trailing unknowns in the door struct, moving to the next door in the packet.

                Buffer.SkipBytes(32);

                string DestZone = "NONE";

                Door NewDoor = new Door(DoorName, YPos, XPos, ZPos, Heading, Incline, Size, DoorID, OpenType, StateAtSpawn, InvertState,
                                        DoorParam, DestZone, 0, 0, 0, 0);

                DoorList.Add(NewDoor);
            }
            return(DoorList);
        }
예제 #7
0
        public SegmentACK(ByteStream queue)
        {
            byte b = queue.ReadByte();

            IsNegativeAck = (b & 2) != 0;
            IsServer      = (b & 1) != 0;

            OriginalInvokeId = queue.ReadByte();
            SequenceNumber   = queue.popU1B();
            ActualWindowSize = queue.popU1B();
        }
예제 #8
0
        public UnconfirmedRequest(ServicesSupported services, ByteStream queue)
        {
            queue.ReadByte();
            byte choiceId = queue.ReadByte();

            Service = UnconfirmedRequestService.createUnconfirmedRequestService(services, choiceId, queue);
            if (Service == null)
            {
                throw new BACnetErrorException(ErrorClass.Device, ErrorCode.ServiceRequestDenied);
            }
        }
예제 #9
0
        public BVLC(ByteStream source)
        {
            // Initial parsing of IP message.
            // BACnet/IP
            type = (BVLCType)source.ReadByte();
            if (type != BVLCType.BACnetIP_AnnexJ) // NO BVLC !!
            {
                throw new MessageValidationAssertionException("Protocol id is not BACnet/IP (0x81)");
            }

            function = (BVLCFunction)source.ReadByte();
            if (function != BVLCFunction.OriginalUnicastNPDU &&
                function != BVLCFunction.OriginalBroadcastNPDU &&
                function != BVLCFunction.ForwardedNPDU &&
                function != 0x0)
            {
                throw new MessageValidationAssertionException("Function is not unicast, broadcast, forward"
                                                              + " or foreign device reg anwser (0xa, 0xb, 0x4 or 0x0)");
            }

            length = source.ReadShort();
            if (length != source.Length /* + 4*/)
            {
                throw new MessageValidationAssertionException("Length field does not match data: given=" + length
                                                              + ", expected=" + (source.Length /* + 4*/));
            }

            // answer to foreign device registration
            if (function == 0x0)
            {
                int regResult = source.ReadShort();
                if (regResult != 0)
                {
                    Debug.Print("Foreign device registration not successful! result: " + regResult);
                }

                // not APDU received, bail
                //return null; // TODO Test
            }

            if (function == BVLCFunction.ForwardedNPDU)
            {
                // A forward. Use the address/port as the link service address.
                byte[] addr = new byte[6];
                source.Read(addr);
                var linkService = new OctetString(addr);
            }
        }
예제 #10
0
        protected long readTag(ByteStream queue)
        {
            byte b         = queue.ReadByte();
            int  tagNumber = (b & 0xff) >> 4;

            ContextSpecific = (b & 8) != 0;
            long length = (b & 7);

            if (tagNumber == 0xf)
            {
                // Extended tag.
                tagNumber = queue.popU1B();
            }

            if (length == 5)
            {
                length = queue.popU1B();
                if (length == 254)
                {
                    length = queue.popU2B();
                }
                else if (length == 255)
                {
                    length = queue.popU4B();
                }
            }

            return(length);
        }
예제 #11
0
 public void TestByteStreamReading()
 {
     // Test bytes
     using (ByteStream stream = new ByteStream(testData))
     {
         for (int i = 0; i < testData.Length; i++)
         {
             Assert.AreEqual(testData[i], stream.ReadByte(), "ReadByte returned incorrect value");
         }
     }
     // Test ushorts
     using (ByteStream stream = new ByteStream(testData))
     {
         Assert.AreEqual(0x0841, stream.ReadUshort());
         Assert.AreEqual(0x6472, stream.ReadUshort());
         Assert.AreEqual(0x6965, stream.ReadUshort());
         Assert.AreEqual(0x6e6e, stream.ReadUshort());
     }
     // Test uints
     using (ByteStream stream = new ByteStream(testData))
     {
         Assert.AreEqual(0x08416472, stream.ReadUint());
         Assert.AreEqual(0x69656e6e, stream.ReadUint());
     }
     // Test string
     using (ByteStream stream = new ByteStream(testData))
     {
         Assert.AreEqual("Adrienne", stream.ReadString(stream.ReadByte(), Encoding.ASCII));
     }
 }
예제 #12
0
    /// <summary>
    /// 读取二进制转换为结构
    /// </summary>
    /// <returns></returns>
    public ReceivePacket Read(int cmd, ByteStream recvStream, int len)
    {
        ServerMessage msg = serverMessageData.GetServerMessage(cmd);

        if (msg == null)
        {
            return(null);
        }
        ReceivePacket p = new ReceivePacket
        {
            cmd      = cmd,
            callback = msg.callback.Method,
        };

        byte[] msgbody = recvStream.ReadByte(len);
        if (msgbody == null || msgbody.Length == 0)
        {
            p.protoObj = Activator.CreateInstance(msg.msgType);
            return(p);
        }

        MemoryStream stream = new MemoryStream(msgbody);

        stream.SetLength(msgbody.Length);
        try
        {
            p.protoObj = RuntimeTypeModel.Default.Deserialize(stream, null, msg.msgType);
        }
        catch (Exception)
        {
            Debug.LogError("protobuf反序列化失败");
        }

        return(p);
    }
예제 #13
0
        /// <summary>
        ///     Decodes this instance.
        /// </summary>
        internal void Decode(byte[] buffer, int length)
        {
            ByteStream stream = new ByteStream(buffer, length);

            this._protocolVersion = stream.ReadByte();

            if (this._protocolVersion <= 2)
            {
                if (!stream.IsAtEnd())
                {
                    int    messageType   = stream.ReadVInt();
                    int    messageLength = stream.ReadVInt();
                    byte[] messageBytes  = stream.ReadBytes(messageLength, 0x7FFFFFFF);

                    this._message = NetMessageFactory.CreateMessageByType(messageType);

                    if (this._message == null)
                    {
                        Logging.Error("NetPacket::decode unknown message received, type: " + messageType);
                        return;
                    }

                    this._message.GetByteStream().SetByteArray(messageBytes, messageLength);
                }
            }
            else
            {
                Logging.Warning("NetPacket::decode invalid protocol version");
            }
        }
예제 #14
0
        internal ComplexACK(ByteStream queue)
        {
            byte b = queue.ReadByte();

            expectsReply  = (b & 8) != 0;
            IsMoreFollows = (b & 4) != 0;

            OriginalInvokeId = queue.ReadByte();
            if (expectsReply)
            {
                SequenceNumber     = queue.popU1B();
                ProposedWindowSize = queue.popU1B();
            }
            serviceChoice = queue.ReadByte();
            serviceData   = new ByteStream(queue.ReadToEnd());
        }
예제 #15
0
        void ProcessDirectoryUpdateAck(DataPacket dp, ByteStream data)
        {
            //DirecotyQueryType responseType = (DirecotyQueryType)parent.RetrieveRequestID(dp.SNAC.RequestID);

            Byte success = data.ReadByte();     // 0x0a

            ushort responseLength = data.ReadUshortLE();

            Debug.Assert(responseLength == data.RemainingBytes);

            // Read Sub Snac Header
            SNACHeader shsub = data.ReadSnacHeader();

            // Reads Snac Extra Bytes
            ushort snacExtraBytesLength = data.ReadUshort();

            if (snacExtraBytesLength > 0)
            {
                // Version or Anything
                if (snacExtraBytesLength == 6)
                {
                    ushort snacExtraBytesTyp   = data.ReadUshort();
                    ushort snacExtraBytesLen   = data.ReadUshort();
                    ushort snacExtraBytesValue = data.ReadUshort(); // VersionsNr
                }
                else
                {
                    data.ReadByteArray(snacExtraBytesLength);
                }
            }

            Byte result = data.ReadByte();      // 0x01

            if (result != 1)
            {
                Logging.WriteString("Error: Directory update request failed, status {0}", result);
                return;
            }

            ushort errorLength = data.ReadUshort();

            if (errorLength > 0)
            {
                data.ReadByteArray(errorLength);
                Logging.WriteString("Warning: Data in error message present!");
            }
        }
예제 #16
0
        public static long getLong(this ByteStream stream) {
            ulong v = 0;
            for (byte i = 0; i < sizeof(ulong); ++i) {
                //Log.Trace("Removing one byte from steam at position: " + stream.Position + " / " + stream.Length, "getLong");
                v |= (ulong)((ulong)(stream.ReadByte()) << (i * 8));
            }

            return (long)v;
        }
예제 #17
0
    void OnMsg(ByteStream stream)
    {
        byte frame = stream.ReadByte();
        byte way   = stream.ReadByte();

        if (frame == 1)
        {
            switch (way)
            {
            case 0:
                Debug.Log("收到心跳:" + stream.ReadInt());
                break;

            case 1:
                Debug.Log("收到登录返回");
                break;
            }
        }
    }
예제 #18
0
 //
 // Reading and writing
 //
 public Date(ByteStream queue)
 {
     readTag(queue);
     Year  = queue.popU1B();
     Month = queue.popU1B();
     Day   = queue.popU1B();
     // TODO dayOfWeek = DayOfWeek.valueOf(queue.pop());
     // DayOfWeek = DayOfWeek.Monday;
     DayOfWeek = (DayOfWeek)queue.ReadByte(); // TODO test
 }
예제 #19
0
        public override void ExploreSpawnDoor(StreamWriter outputStream, ByteStream buffer, PacketDirection direction)
        {
            uint DoorCount = buffer.Length() / 96;

            outputStream.WriteLine("Door Count: {0}", DoorCount);

            for (int d = 0; d < DoorCount; ++d)
            {
                string DoorName = buffer.ReadFixedLengthString(32, false);


                float YPos = buffer.ReadSingle();

                float XPos = buffer.ReadSingle();

                float ZPos = buffer.ReadSingle();

                float Heading = buffer.ReadSingle();

                UInt32 Incline = buffer.ReadUInt32();

                Int32 Size = buffer.ReadInt32();

                buffer.SkipBytes(4); // Skip Unknown

                Byte DoorID = buffer.ReadByte();

                Byte OpenType = buffer.ReadByte();

                Byte StateAtSpawn = buffer.ReadByte();

                Byte InvertState = buffer.ReadByte();

                Int32 DoorParam = buffer.ReadInt32();

                outputStream.WriteLine(" Name: {0} ID: {1} OT: {2} SAS: {3} IS: {4} DP: {5}",
                                       DoorName, DoorID, OpenType, StateAtSpawn, InvertState, DoorParam);

                // Skip past the trailing unknowns in the door struct, moving to the next door in the packet.

                buffer.SkipBytes(28);
            }
        }
예제 #20
0
        /// <summary>
        /// Decodes this instance.
        /// </summary>
        public void Decode(ByteStream Stream)
        {
            this.Type   = Stream.ReadByte();
            this.HighId = Stream.ReadVInt();
            this.LowId  = Stream.ReadVInt();

            Stream.DecodeIntList(ref this.Ticks);
            Stream.DecodeIntList(ref this.Coords);
            Stream.DecodeIntList(ref this.Params);

            if (this.Type == 7)
            {
                Logging.Info(this.GetType(), "Unknown Value: " + Stream.ReadByte());
            }

            if (this.Type == 8)
            {
                Logging.Info(this.GetType(), "Unknown Boolean: " + Stream.ReadByte());
            }
        }
예제 #21
0
        public void TestByteStream()
        {
            byte[] data = new byte[1024];
            for (int i = 0; i < 1024; i++)
            {
                data[i] = (byte)(i % 256);
            }

            ByteStream bStream = new ByteStream(data);

            byte[] buffer = new byte[512];
            bStream.Read(buffer, 0, 512);
            for (int bufferIndex = 0; bufferIndex < buffer.Length; bufferIndex++)
            {
                if (buffer[bufferIndex] != bufferIndex % 256)
                {
                    throw new Exception("Expecting " + (bufferIndex).ToString());
                }
            }

            bStream.Seek(0, SeekOrigin.Begin);
            if (bStream.ReadByte() != 0)
            {
                throw new Exception("Expecting expected 0");
            }

            if (bStream.ReadByte() != 1)
            {
                throw new Exception("Expecting expected 1");
            }

            bStream.Seek(510, SeekOrigin.Current);
            bStream.Read(buffer, 0, 512);
            for (int i = 0; i < buffer.Length; i++)
            {
                if (buffer[i] != (i + 512) % 256)
                {
                    throw new Exception("Expecting " + (i + 512).ToString());
                }
            }
        }
예제 #22
0
        public ConfirmedRequest(ServicesSupported servicesSupported, ByteStream queue)
        {
            byte b = queue.ReadByte();

            IsSegmentedMessage          = (b & 8) != 0;
            IsMoreFollows               = (b & 4) != 0;
            IsSegmentedResponseAccepted = (b & 2) != 0;

            b = queue.ReadByte();
            MaxSegmentsAccepted   = (MaxSegments)((byte)((b & 0x70) >> 4));
            MaxApduLengthAccepted = (MaxApduLength)((byte)(b & 0xf));
            InvokeId = queue.ReadByte();
            if (IsSegmentedMessage)
            {
                SequenceNumber     = queue.popU1B();
                ProposedWindowSize = queue.popU1B();
            }
            serviceChoice = queue.ReadByte();
            ServiceData   = new ByteStream(queue.ReadToEnd());

            ConfirmedRequestService.checkConfirmedRequestService(servicesSupported, serviceChoice);
        }
예제 #23
0
        public NPDU(ByteStream source)
        {
            version = source.ReadByte();
            control = new NLPCI(source.ReadByte());

            if (control.IsDestinationSpecific)
            {
                destinationNetworkAddress       = source.popU2B();
                destinationMacLyerAddressLength = source.popU1B();
                if (destinationMacLyerAddressLength > 0)
                {
                    destinationAddress = new byte[destinationMacLyerAddressLength];
                    source.Read(destinationAddress);
                }
            }

            if (control.IsSourceSpecific)
            {
                // TODO Check address length
                sourceNetworkAddress       = source.popU2B();
                sourceMacLyerAddressLength = source.popU1B();
                sourceAddress = new byte[sourceMacLyerAddressLength];
                source.Read(destinationAddress);
            }

            if (control.IsDestinationSpecific)
            {
                hopCount = source.popU1B();
            }

            if (control.IsNetworkLayerMessage)
            {
                messageType = source.popU1B();
                if (messageType >= 80)
                {
                    vendorId = source.popU2B();
                }
            }
        }
예제 #24
0
        //
        // Reading and writing
        //
        public CharacterString(ByteStream queue)
        {
            int length = (int)readTag(queue);

            //byte enc = queue.ReadByte();
            //Encoding = Encodings.ANSI_X3_4;
            Encoding = (Encodings)queue.ReadByte();
            validateEncoding();

            byte[] bytes = new byte[length - 1];
            queue.Read(bytes);

            Value = decode(Encoding, bytes);
        }
예제 #25
0
        public void TestByteStreamNumberWriting()
        {
            ByteStream stream = new ByteStream();

            stream.WriteByte(0x08);
            stream.WriteUshort(0x4164);
            stream.WriteUint(0x7269656e);
            stream.WriteByteArray(new byte[] { 0x6e, 0x65 });

            Assert.AreEqual(testData.Length, stream.GetByteCount());
            ByteStream testStream = new ByteStream(stream.GetBytes());

            Assert.AreEqual("Adrienne", testStream.ReadString(testStream.ReadByte(), Encoding.ASCII));
        }
예제 #26
0
        public void ByteStream_Byte_Test()
        {
            var bs = new ByteStream(new byte[10]);

            for (int i = 0; i < bs.DataLength; i++)
            {
                bs.WriteByte((byte)i);
            }
            bs.ResetCurrentOffset();
            for (int i = 0; i < bs.DataLength; i++)
            {
                Assert.AreEqual((byte)i, bs.ReadByte());
            }
        }
예제 #27
0
 static int ReadByte(IntPtr L)
 {
     try
     {
         ToLua.CheckArgsCount(L, 1);
         ByteStream obj = (ByteStream)ToLua.CheckObject <ByteStream>(L, 1);
         byte       o   = obj.ReadByte();
         LuaDLL.lua_pushnumber(L, o);
         return(1);
     }
     catch (Exception e)
     {
         return(LuaDLL.toluaL_exception(L, e));
     }
 }
예제 #28
0
        public static string getString(this ByteStream stream) {
            //Log.Trace(String.Format("Deserializing stream at pos {0}", stream.Position), "getString");
            // Read length
            ushort len = stream.getUShort();
            //Log.Trace(String.Format("Deserialized string length as {0}", len), "getString");

            // Read data
            char[] cstr = new char[len];

            if (len > 0)
                for (ushort i = 0; i < len; ++i)
                    cstr[i] = (char)stream.ReadByte();

            //Log.Trace(String.Format("Finished deserializing stream at pos {0}", stream.Position), "getString");
            return new string(cstr);
        }
        public void Decode(ByteStream stream, LogicMessageFactory factory)
        {
            this.m_messageId = stream.ReadByte();
            int messageType = stream.ReadVInt();

            this.m_piranhaMessage = factory.CreateMessageByType(messageType);

            if (this.m_piranhaMessage != null)
            {
                int encodingLength = stream.ReadVInt();
                this.m_piranhaMessage.GetByteStream().SetByteArray(stream.ReadBytes(encodingLength, 900000), encodingLength);
            }
            else
            {
                Debugger.Warning("UdpMessage::decode unable to read message type " + messageType);
            }
        }
예제 #30
0
        private void openHighMapToolStripMenuItem_Click(object sender, EventArgs e)
        {
            var dialog = new OpenFileDialog();

            dialog.InitialDirectory = Path.GetFullPath(directorySave);
            dialog.Filter           = "IsoHightMap(*.IHM)|*.ihm|All files (*.*)|*.*";
            dialog.FileOk          += new CancelEventHandler((object csender, CancelEventArgs ce) =>
            {
                ByteStream bs = new ByteStream(dialog.FileName);
                bs.ReadByte();
                Program.MainForm.renderer.Data            = new RenderData(bs.ReadInt(), bs.ReadInt());
                Program.MainForm.renderer.Data.HeightMap  = bs.ReadByteArray();
                Program.MainForm.renderer.Data.TextureMap = bs.ReadByteArray();
                Program.MainForm.Repainting = true;
                directorySave = Path.GetDirectoryName(dialog.FileName);
            });
            dialog.ShowDialog(this);
        }
예제 #31
0
 private static void DecodeColumn(ByteStream stream, byte[] columnOut, int compressed)
 {
     if (compressed == 0) {
         // uncompressed.
         for (int y = 0; y < columnOut.Length; ++y) {
             columnOut[y] = (byte)stream.ReadByte();
         }
     } else if (compressed == 1) {
         // rle1
         for (int y = 0; y < columnOut.Length; ) {
             int code = stream.ReadByte();
             if (code > 128) {
                 byte color = (byte)stream.ReadByte();
                 int repeat = code & 0x7f;
                 while (repeat-- > 0) {
                     columnOut[y++] = color;
                 }
             } else {
                 while (code-- > 0) {
                     columnOut[y++] = (byte)stream.ReadByte();
                 }
             }
         }
     } else if (compressed == 2) {
         // rle2 (transparent coding)
         for (int y = 0; y < columnOut.Length; ) {
             int code = stream.ReadByte();
             if (code > 128) {
                 int skip = code & 0x7f;
                 while (skip-- > 0) {
                     columnOut[y++] = 0;
                 }
             } else {
                 while (code-- > 0) {
                     columnOut[y++] = (byte)stream.ReadByte();
                 }
             }
         }
     }
 }
예제 #32
0
        /// <summary>
        /// Creates a new <see cref="ChatRoom"/> from a received <see cref="ByteStream"/>
        /// </summary>
        public ChatRoom(ByteStream stream)
        {
            exchangeNumber = stream.ReadUshort();
            fullName = stream.ReadString(stream.ReadByte(), Encoding.ASCII);
            instance = stream.ReadUshort();

            // A small chat room info block will only contain the bare essentials:
            // exchange number, chat room name, and instance number.
            // The chat room class really wants a display name, so parse one here.
            if (stream.HasMoreData)
            {
                detailLevel = stream.ReadByte();
                unknownCode = stream.ReadUshort(); // No idea what this is

                using (TlvBlock block = new TlvBlock(stream.ReadByteArrayToEnd()))
                {
                    flags = block.ReadUshort(CHATROOM_FLAGS);
                    if (block.HasTlv(CHATROOM_CREATION_TIME))
                    {
                        creationTime = block.ReadDateTime(CHATROOM_CREATION_TIME);
                    }
                    maxMessageLength = block.ReadUshort(CHATROOM_MESSAGE_LENGTH);
                    maxOccupants = block.ReadUshort(CHATROOM_MAX_OCCUPANTS);
                    displayName = block.ReadString(CHATROOM_DISPLAYNAME, Encoding.ASCII);
                    creationPermissions = block.ReadByte(CHATROOM_PERMISSIONS);

                    string charset = block.ReadString(CHATROOM_CHARSET1, Encoding.ASCII);
                    if (!String.IsNullOrEmpty(charset))
                    {
                        charSet1 = Encoding.GetEncoding(charset);
                    }
                    language1 = block.ReadString(CHATROOM_LANGUAGE1, Encoding.ASCII);

                    charset = block.ReadString(CHATROOM_CHARSET2, Encoding.ASCII);
                    if (!String.IsNullOrEmpty(charset))
                    {
                        charSet2 = Encoding.GetEncoding(charset);
                    }
                    language2 = block.ReadString(CHATROOM_LANGUAGE2, Encoding.ASCII);

                    contentType = block.ReadString(CHATROOM_CONTENTTYPE, Encoding.ASCII);
                }
            }

            // Make sure there's a display name to show
            if (String.IsNullOrEmpty(displayName))
            {
                Match match = AolUriParser.Match(fullName);
                if (match.Success)
                {
                    //displayName = UtilityMethods.DeHexUri(match.Groups["roomname"].Value);
                    int lastDashBeforeName = fullName.IndexOf('-', 16);
                    displayName = fullName.Substring(lastDashBeforeName + 1);
                }
                else
                {
                    displayName = fullName;
                }
            }
        }
예제 #33
0
    private Header ReadHeader(ByteStream stream, EHeaderType headerType)
    {
        Header header = new Header();

        if (headerType == EHeaderType.FileHeader) {
            header.W = stream.ReadLittleShort16();
            header.H = stream.ReadLittleShort16();
            stream.Skip(2);
            header.IY = stream.ReadLittleShort16();
            header.Transparent = stream.ReadByte();
            stream.Skip(1);
            header.Compressed = stream.ReadLittleShort16();
            header.DataSize = stream.ReadLittleInt32();
            stream.Skip(12);
        } else {
            header.W = stream.ReadLittleShort16();
            header.H = stream.ReadLittleShort16();
            stream.Skip(20);
            header.Transparent = stream.ReadByte();
            stream.Skip(3);
        }

        return header;
    }
예제 #34
0
    private void ParseBitmap(ByteStream stream, CreateArgs createArgs)
    {
        if ((stream.ReadString(3) != "BM ") || (stream.ReadByte() != 0x1e)){
            throw new InvalidDataException("Not a BM file.");
        }

        Header header = ReadHeader(stream, EHeaderType.FileHeader);
        DebugCheck.Assert(stream.Position == 32);

        if ((header.W == 1) && (header.H != 1)) {
            // multiple bitmaps in this file.
            _fps = stream.ReadByte();
            stream.Skip(1);

            long baseOfs = stream.Position;

            int[] offsets = new int[header.IY];
            for (int i = 0; i < offsets.Length; ++i) {
                offsets[i] = stream.ReadLittleInt32();
            }

            for (int i = 0; i < offsets.Length; ++i) {
                stream.SeekSet(offsets[i] + baseOfs);
                Header subHeader = ReadHeader(stream, EHeaderType.SubHeader);
                Frame frame = ReadColumns(stream, subHeader, null, createArgs);
                _frames.Add(frame);
            }
        } else {
            int[] columnOffsets = null;

            if (header.Compressed != 0) {
                // read column offsets.
                stream.SeekSet(header.DataSize);
                columnOffsets = new int[header.W];

                for (int i = 0; i < columnOffsets.Length; ++i) {
                    columnOffsets[i] = stream.ReadLittleInt32() + 32;
                }
            }

            Frame frame = ReadColumns(stream, header, columnOffsets, createArgs);
            _frames.Add(frame);
        }
    }