ReadBytes() public method

public ReadBytes ( ) : byte[]
return byte[]
        internal NetworkP2PHandoverInstance(NetBuffer buffer)
        {
            _networkView = null;

            position   = new Vector3(buffer.ReadFloat(), buffer.ReadFloat(), buffer.ReadFloat());
            rotation   = new Quaternion(buffer.ReadFloat(), buffer.ReadFloat(), buffer.ReadFloat(), buffer.ReadFloat());
            relativeTo = (NetworkP2PSpace)buffer.ReadByte();

            remoteViewID           = new NetworkViewID(buffer);
            group                  = new NetworkGroup(buffer);
            authFlags              = (NetworkAuthFlags)buffer.ReadByte();
            isInstantiatedRemotely = buffer.ReadBoolean();

            proxyPrefab  = buffer.ReadString();
            ownerPrefab  = buffer.ReadString();
            serverPrefab = buffer.ReadString();

            cellAuthPrefab  = buffer.ReadString();
            cellProxyPrefab = buffer.ReadString();

            uint initialSize = buffer.ReadVariableUInt32();

            _initialData = initialSize != 0 ? buffer.ReadBytes((int)initialSize) : new byte[0];

            uint handoverSize = buffer.ReadVariableUInt32();

            _handoverData = handoverSize != 0 ? buffer.ReadBytes((int)handoverSize) : new byte[0];

            _isInstantiatable = true;
            _networkP2P       = null;
        }
Esempio n. 2
0
    public void BunchOfBytesCanBeReadAtOnce()
    {
        buffer.ReadBytes(tempArray, bufferLength);

        for (var i = 0; i < bufferLength; i++)
        {
            Assert.AreEqual(bytes[i], tempArray[i], "ReadBytes function read a bunch of bytes at once and value of '" + i + "' byte is incorrect");
        }

        Assert.AreEqual(bufferLength, buffer.Position, "ReadBytes function changed position incorrectly after read a bunch of bytes");
    }
        public decimal ReadDecimal()
        {
            var bytes = _buffer.ReadBytes(16);

            using (MemoryStream memory = new MemoryStream(bytes))
            {
                using (BinaryReader reader = new BinaryReader(memory))
                {
                    return(reader.ReadDecimal());
                }
            }
        }
Esempio n. 4
0
        public void Read(NetBuffer im)
        {
            MetaData = im.ReadString();
            int l = im.ReadInt32();

            Data = im.ReadBytes(l);
        }
Esempio n. 5
0
        public void Read(NetBuffer buffer)
        {
            Files.Clear();
            SyncType = (FileSyncType)buffer.ReadByte();

            if (SyncType == FileSyncType.Manifest)
            {
                DownloadUrl = buffer.ReadString();
            }

            if (SyncType == FileSyncType.Manifest ||
                SyncType == FileSyncType.Request)
            {
                var fileCount = buffer.ReadInt32();
                for (int i = 0; i < fileCount; i++)
                {
                    var fi = new FSFileInfo();
                    fi.RelativePath = buffer.ReadString();
                    fi.WorkshopId   = buffer.ReadUInt64();

                    if (SyncType == FileSyncType.Manifest)
                    {
                        fi.Hash = buffer.ReadBytes(16);
                    }
                    Files.Add(fi);
                }
            }
        }
Esempio n. 6
0
 /// <inheritdoc />
 public void ReadFromBuffer(NetBuffer buffer)
 {
     Id   = new Guid(buffer.ReadBytes(16));
     Type = (GamePieceType)buffer.ReadByte();
     X    = buffer.ReadFloat();
     Y    = buffer.ReadFloat();
 }
Esempio n. 7
0
        public virtual bool Read(NetBuffer msg)
        {
            if (!CanReceive)
            {
                throw new Exception("Called Read on a VoipQueue not set up for receiving");
            }

            UInt16 incLatestBufferID = msg.ReadUInt16();

            if (firstRead || NetIdUtils.IdMoreRecent(incLatestBufferID, LatestBufferID))
            {
                firstRead = false;
                for (int i = 0; i < BUFFER_COUNT; i++)
                {
                    bufferLengths[i] = msg.ReadByte();
                    msg.ReadBytes(buffers[i], 0, bufferLengths[i]);
                }
                newestBufferInd = BUFFER_COUNT - 1;
                LatestBufferID  = incLatestBufferID;
                LastReadTime    = DateTime.Now;
                return(true);
            }
            else
            {
                for (int i = 0; i < BUFFER_COUNT; i++)
                {
                    byte len = msg.ReadByte();
                    msg.Position += len * 8;
                }
                return(false);
            }
        }
Esempio n. 8
0
 public NetMessage Deserialize(NetBuffer buffer)
 {
     head.Deserialize(buffer);
     content = new byte[head.dataSize];
     buffer.ReadBytes(content, 0, head.dataSize);
     return(this);
 }
 public static void ReadInto(this NetBuffer from, NetBuffer to, int byteCount)
 {
     to.EnsureBufferSize(byteCount * 8);
     from.ReadBytes(to.Data, offset: 0, numberOfBytes: byteCount);
     to.LengthBytes = byteCount;
     to.ResetReader();
 }
Esempio n. 10
0
    public void AttemptToReadABunchOfBytesOutOfBufferBounds_OutOfRangeExceptionRaises()
    {
        var testBuffer = new NetBuffer(new byte[1]);

        Assert.That(() => testBuffer.ReadBytes(new byte[2], 2),
                    Throws.Exception.TypeOf <IndexOutOfRangeException>()
                    .With.Message.EqualTo("NetworkReader:ReadBytes out of range: (2) NetBuf sz:1 pos:0"));
    }
Esempio n. 11
0
 public void Read(NetBuffer buffer)
 {
     File        = buffer.ReadString().ToLower();
     TotalLength = buffer.ReadInt64();
     ChunkLength = buffer.ReadInt32();
     Data        = buffer.ReadBytes(ChunkLength);
     Temporary   = buffer.ReadBoolean();
 }
Esempio n. 12
0
 public void Read(NetBuffer buffer)
 {
     EntityId     = buffer.ReadInt32();
     EntityTypeId = buffer.ReadByte();
     ChangedTick  = buffer.ReadInt32();
     ChangedTime  = buffer.ReadSingle();
     PropDataSize = buffer.ReadInt32();
     PropData     = buffer.ReadBytes(PropDataSize);
 }
Esempio n. 13
0
        public void Read(NetBuffer im)
        {
            MessagePacketId = im.ReadInt64();
            Number          = im.ReadInt32();
            int length = im.ReadInt32();

            if (length != 0)
            {
                Bytes = im.ReadBytes(length);
            }
        }
Esempio n. 14
0
        public static void Read <T>(this NetBuffer buffer, out T s)
            where T : struct
        {
            var size  = Marshal.SizeOf(typeof(T));
            var array = buffer.ReadBytes(size);
            var ptr   = Marshal.AllocHGlobal(size);

            Marshal.Copy(array, 0, ptr, size);
            s = (T)Marshal.PtrToStructure(ptr, typeof(T));
            Marshal.FreeHGlobal(ptr);
        }
Esempio n. 15
0
        public static byte[] ReadBytes(NetBuffer buffer)
        {
            byte[] data = null;
            int    len  = buffer.ReadInt32();

            if (len > 0)
            {
                data = buffer.ReadBytes(len);
            }

            return(data);
        }
Esempio n. 16
0
 public bool Deserialize(NetBuffer buffer)
 {
     if (head.Deserialize(buffer))
     {
         if (buffer.BytesAvailable >= head.dataSize)
         {
             content = new byte[head.dataSize];
             buffer.ReadBytes(content, 0, (int)head.dataSize);
             return(true);
         }
     }
     return(false);
 }
Esempio n. 17
0
        public override int Read(byte[] buffer, int offset, int count)
        {
            var bytesAvailable = _buffer.LengthBytes - _buffer.PositionInBytes;

            if (bytesAvailable < count)
            {
                count = bytesAvailable;
            }

            _buffer.ReadBytes(buffer, offset, count);

            return(count);
        }
Esempio n. 18
0
        public void Read(NetBuffer buffer)
        {
            GameVersion = buffer.ReadString();
            DisplayName = buffer.ReadString();
            Password    = buffer.ReadString();
            SteamID     = buffer.ReadUInt64();

            var len = buffer.ReadInt32();

            if (len > 0)
            {
                TicketData = buffer.ReadBytes(len);
            }
        }
Esempio n. 19
0
 public void Read(NetBuffer im)
 {
     PluginName = im.ReadString();
     MethodName = im.ReadString();
     RspType    = im.ReadByte();
     if (RspType == StringDataType)
     {
         StringCommandRsp = im.ReadString();
     }
     else if (RspType == BinaryDataType)
     {
         int l = im.ReadInt32();
         BinaryCommandRsp = im.ReadBytes(l);
     }
 }
Esempio n. 20
0
        public void Read(NetBuffer buffer)
        {
            DataEntries.Clear();

            Label = buffer.ReadString();
            byte entryCount = buffer.ReadByte();

            for (int i = 0; i < entryCount; i++)
            {
                var entry = new DataEntry();
                entry.Type = (DataType)buffer.ReadByte();
                switch (entry.Type)
                {
                case DataType.Bool:
                    entry.BoolValue = buffer.ReadBoolean();
                    break;

                case DataType.Int:
                    entry.IntValue = buffer.ReadInt32();
                    break;

                case DataType.Float:
                    entry.FloatValue = buffer.ReadSingle();
                    break;

                case DataType.Byte:
                    entry.ByteValue = buffer.ReadByte();
                    break;

                case DataType.String:
                    entry.StringValue = buffer.ReadString();
                    break;

                case DataType.Vector3:
                    entry.Vector3Value = buffer.ReadVector3();
                    break;

                case DataType.Bytes:
                    var byteCount = buffer.ReadInt32();
                    entry.BytesValue = buffer.ReadBytes(byteCount);
                    break;
                }

                DataEntries.Add(entry);
            }
        }
Esempio n. 21
0
        /// <inheritdoc />
        public void ReadFromBuffer(NetBuffer buffer)
        {
            RoomId        = buffer.ReadString();
            YourPlayer    = buffer.ReadInt32();
            CurrentPlayer = new Guid(buffer.ReadBytes(16));

            Players = new Player[buffer.ReadInt32()];
            for (var i = 0; i < Players.Length; i++)
            {
                Players[i] = buffer.ReadClass <Player>();
            }

            Board = new GamePiece[buffer.ReadInt32()];
            for (var i = 0; i < Board.Length; i++)
            {
                Board[i] = buffer.ReadClass <GamePiece>();
            }
        }
Esempio n. 22
0
        public static T ReadStruct <T>(this NetBuffer buffer) where T : struct
        {
            var str = new T();

            var size = Marshal.SizeOf(str);

            if (size == 0)
            {
                return(str);
            }

            var ptr = Marshal.AllocHGlobal(size);

            var arr = buffer.ReadBytes(size);

            Marshal.Copy(arr, 0, ptr, size);

            str = (T)Marshal.PtrToStructure(ptr, str.GetType());
            Marshal.FreeHGlobal(ptr);

            return(str);
        }
Esempio n. 23
0
        static unsafe void Main(string[] args)
        {
            // JIT stuff
            NetBuffer msg = new NetBuffer(20);

            msg.Write((short)short.MaxValue);

            // Go
            double timeStart = NetTime.Now;

            msg = new NetBuffer(20);
            for (int n = 0; n < 10000; n++)
            {
                msg.Reset();

                msg.Write((short)short.MaxValue);
                msg.Write((short)short.MinValue);
                msg.Write((short)-42);

                msg.Write(421);
                msg.Write((byte)7);
                msg.Write(-42.8f);

                if (msg.LengthBytes != 15)
                {
                    throw new Exception("Bad message length");
                }

                msg.Write("duke of earl");

                int bytesWritten;
                bytesWritten = msg.WriteVariableInt32(-1);
                bytesWritten = msg.WriteVariableInt32(5);
                bytesWritten = msg.WriteVariableInt32(-18);
                bytesWritten = msg.WriteVariableInt32(42);
                bytesWritten = msg.WriteVariableInt32(-420);

                msg.Write((uint)9991);

                // byte boundary kept until here

                msg.Write(true);
                msg.Write((uint)3, 5);
                msg.Write(8.111f);
                msg.Write("again");
                byte[] arr = new byte[] { 1, 6, 12, 24 };
                msg.Write(arr);
                msg.Write((byte)7, 7);
                msg.Write(Int32.MinValue);
                msg.Write(UInt32.MaxValue);
                msg.WriteRangedSingle(21.0f, -10, 50, 12);

                // test reduced bit signed writing
                msg.Write(15, 5);
                msg.Write(2, 5);
                msg.Write(0, 5);
                msg.Write(-1, 5);
                msg.Write(-2, 5);
                msg.Write(-15, 5);

                msg.Write(UInt64.MaxValue);
                msg.Write(Int64.MaxValue);
                msg.Write(Int64.MinValue);

                msg.Write(42);
                msg.WritePadBits();

                int numBits = msg.WriteRangedInteger(0, 10, 5);
                if (numBits != 4)
                {
                    throw new Exception("Ack WriteRangedInteger failed");
                }

                // verify
                msg.Position = 0;

                short a = msg.ReadInt16();
                short b = msg.ReadInt16();
                short c = msg.ReadInt16();

                if (a != short.MaxValue || b != short.MinValue || c != -42)
                {
                    throw new Exception("Ack thpth short failed");
                }

                if (msg.ReadInt32() != 421)
                {
                    throw new Exception("Ack thphth 1");
                }
                if (msg.ReadByte() != (byte)7)
                {
                    throw new Exception("Ack thphth 2");
                }
                if (msg.ReadSingle() != -42.8f)
                {
                    throw new Exception("Ack thphth 3");
                }
                if (msg.ReadString() != "duke of earl")
                {
                    throw new Exception("Ack thphth 4");
                }

                if (msg.ReadVariableInt32() != -1)
                {
                    throw new Exception("ReadVariableInt32 failed 1");
                }
                if (msg.ReadVariableInt32() != 5)
                {
                    throw new Exception("ReadVariableInt32 failed 2");
                }
                if (msg.ReadVariableInt32() != -18)
                {
                    throw new Exception("ReadVariableInt32 failed 3");
                }
                if (msg.ReadVariableInt32() != 42)
                {
                    throw new Exception("ReadVariableInt32 failed 4");
                }
                if (msg.ReadVariableInt32() != -420)
                {
                    throw new Exception("ReadVariableInt32 failed 5");
                }

                if (msg.ReadUInt32() != 9991)
                {
                    throw new Exception("Ack thphth 4.5");
                }

                if (msg.ReadBoolean() != true)
                {
                    throw new Exception("Ack thphth 5");
                }
                if (msg.ReadUInt32(5) != (uint)3)
                {
                    throw new Exception("Ack thphth 6");
                }
                if (msg.ReadSingle() != 8.111f)
                {
                    throw new Exception("Ack thphth 7");
                }
                if (msg.ReadString() != "again")
                {
                    throw new Exception("Ack thphth 8");
                }
                byte[] rrr = msg.ReadBytes(4);
                if (rrr[0] != arr[0] || rrr[1] != arr[1] || rrr[2] != arr[2] || rrr[3] != arr[3])
                {
                    throw new Exception("Ack thphth 9");
                }
                if (msg.ReadByte(7) != 7)
                {
                    throw new Exception("Ack thphth 10");
                }
                if (msg.ReadInt32() != Int32.MinValue)
                {
                    throw new Exception("Ack thphth 11");
                }
                if (msg.ReadUInt32() != UInt32.MaxValue)
                {
                    throw new Exception("Ack thphth 12");
                }

                float v = msg.ReadRangedSingle(-10, 50, 12);
                // v should be close to, but not necessarily exactly, 21.0f
                if ((float)Math.Abs(21.0f - v) > 0.1f)
                {
                    throw new Exception("Ack thphth *RangedSingle() failed");
                }

                if (msg.ReadInt32(5) != 15)
                {
                    throw new Exception("Ack thphth ReadInt32 1");
                }
                if (msg.ReadInt32(5) != 2)
                {
                    throw new Exception("Ack thphth ReadInt32 2");
                }
                if (msg.ReadInt32(5) != 0)
                {
                    throw new Exception("Ack thphth ReadInt32 3");
                }
                if (msg.ReadInt32(5) != -1)
                {
                    throw new Exception("Ack thphth ReadInt32 4");
                }
                if (msg.ReadInt32(5) != -2)
                {
                    throw new Exception("Ack thphth ReadInt32 5");
                }
                if (msg.ReadInt32(5) != -15)
                {
                    throw new Exception("Ack thphth ReadInt32 6");
                }

                UInt64 longVal = msg.ReadUInt64();
                if (longVal != UInt64.MaxValue)
                {
                    throw new Exception("Ack thphth UInt64");
                }
                if (msg.ReadInt64() != Int64.MaxValue)
                {
                    throw new Exception("Ack thphth Int64");
                }
                if (msg.ReadInt64() != Int64.MinValue)
                {
                    throw new Exception("Ack thphth Int64");
                }

                if (msg.ReadInt32() != 42)
                {
                    throw new Exception("Ack thphth end");
                }

                msg.SkipPadBits();

                if (msg.ReadRangedInteger(0, 10) != 5)
                {
                    throw new Exception("Ack thphth ranged integer");
                }
            }

            // test writevariableuint64
            NetBuffer largeBuffer = new NetBuffer(100 * 8);

            UInt64[] largeNumbers = new ulong[100];
            for (int i = 0; i < 100; i++)
            {
                largeNumbers[i] = ((ulong)NetRandom.Instance.NextUInt() << 32) | (ulong)NetRandom.Instance.NextUInt();
                largeBuffer.WriteVariableUInt64(largeNumbers[i]);
            }

            largeBuffer.Position = 0;
            for (int i = 0; i < 100; i++)
            {
                UInt64 ln = largeBuffer.ReadVariableUInt64();
                if (ln != largeNumbers[i])
                {
                    throw new Exception("large fail");
                }
            }

            //
            // Extended tests on padbits
            //
            for (int i = 1; i < 31; i++)
            {
                NetBuffer buf = new NetBuffer();
                buf.Write((int)1, i);

                if (buf.LengthBits != i)
                {
                    throw new Exception("Bad length!");
                }

                buf.WritePadBits();
                int wholeBytes = buf.LengthBits / 8;
                if (wholeBytes * 8 != buf.LengthBits)
                {
                    throw new Exception("WritePadBits failed! Length is " + buf.LengthBits);
                }
            }

            NetBuffer small = new NetBuffer(100);

            byte[] rnd  = new byte[24];
            int[]  bits = new int[24];
            for (int i = 0; i < 24; i++)
            {
                rnd[i]  = (byte)NetRandom.Instance.Next(0, 65);
                bits[i] = NetUtility.BitsToHoldUInt((uint)rnd[i]);

                small.Write(rnd[i], bits[i]);
            }

            small.Position = 0;
            for (int i = 0; i < 24; i++)
            {
                byte got = small.ReadByte(bits[i]);
                if (got != rnd[i])
                {
                    throw new Exception("Failed small allocation test");
                }
            }

            double timeEnd  = NetTime.Now;
            double timeSpan = timeEnd - timeStart;

            Console.WriteLine("Trivial tests passed in " + (timeSpan * 1000.0) + " milliseconds");

            Console.WriteLine("Creating client and server for live testing...");

            NetConfiguration config = new NetConfiguration("unittest");

            config.Port = 14242;
            NetServer server       = new NetServer(config);
            NetBuffer serverBuffer = new NetBuffer();

            server.Start();

            config = new NetConfiguration("unittest");
            NetClient client = new NetClient(config);

            client.SetMessageTypeEnabled(NetMessageType.Receipt, true);
            NetBuffer clientBuffer = client.CreateBuffer();

            client.Start();

            client.Connect("127.0.0.1", 14242);

            List <string> events = new List <string>();

            double end        = double.MaxValue;
            double disconnect = double.MaxValue;

            while (NetTime.Now < end)
            {
                double now = NetTime.Now;

                NetMessageType nmt;
                NetConnection  sender;

                //
                // client
                //
                if (client.ReadMessage(clientBuffer, out nmt))
                {
                    switch (nmt)
                    {
                    case NetMessageType.StatusChanged:
                        Console.WriteLine("Client: " + client.Status + " (" + clientBuffer.ReadString() + ")");
                        events.Add("CStatus " + client.Status);
                        if (client.Status == NetConnectionStatus.Connected)
                        {
                            // send reliable message
                            NetBuffer buf = client.CreateBuffer();
                            buf.Write(true);
                            buf.Write((int)52, 7);
                            buf.Write("Hallon");

                            client.SendMessage(buf, NetChannel.ReliableInOrder1, new NetBuffer("kokos"));
                        }

                        if (client.Status == NetConnectionStatus.Disconnected)
                        {
                            end = NetTime.Now + 1.0;                                     // end in one second
                        }
                        break;

                    case NetMessageType.Receipt:
                        events.Add("CReceipt " + clientBuffer.ReadString());
                        break;

                    case NetMessageType.ConnectionRejected:
                    case NetMessageType.BadMessageReceived:
                        throw new Exception("Failed: " + nmt);

                    case NetMessageType.DebugMessage:
                        // silently ignore
                        break;

                    default:
                        // ignore
                        Console.WriteLine("Ignored: " + nmt);
                        break;
                    }
                }

                //
                // server
                //
                if (server.ReadMessage(serverBuffer, out nmt, out sender))
                {
                    switch (nmt)
                    {
                    case NetMessageType.StatusChanged:
                        events.Add("SStatus " + sender.Status);
                        Console.WriteLine("Server: " + sender.Status + " (" + serverBuffer.ReadString() + ")");
                        break;

                    case NetMessageType.ConnectionRejected:
                    case NetMessageType.BadMessageReceived:
                        throw new Exception("Failed: " + nmt);

                    case NetMessageType.Data:
                        events.Add("DataRec " + serverBuffer.LengthBits);
                        bool   shouldBeTrue     = serverBuffer.ReadBoolean();
                        int    shouldBeFifthTwo = serverBuffer.ReadInt32(7);
                        string shouldBeHallon   = serverBuffer.ReadString();

                        if (shouldBeTrue != true ||
                            shouldBeFifthTwo != 52 ||
                            shouldBeHallon != "Hallon")
                        {
                            throw new Exception("Bad data transmission");
                        }

                        disconnect = now + 1.0;
                        break;

                    case NetMessageType.DebugMessage:
                        // silently ignore
                        break;

                    default:
                        // ignore
                        Console.WriteLine("Ignored: " + nmt);
                        break;
                    }
                }

                if (now > disconnect)
                {
                    server.Connections[0].Disconnect("Bye", 0.1f);
                    disconnect = double.MaxValue;
                }
            }

            // verify events
            string[] expected = new string[] {
                "CStatus Connecting",
                "SStatus Connecting",
                "CStatus Connected",
                "SStatus Connected",
                "DataRec 64",
                "CReceipt kokos",
                "SStatus Disconnecting",
                "CStatus Disconnecting",
                "SStatus Disconnected",
                "CStatus Disconnected"
            };

            if (events.Count != expected.Length)
            {
                throw new Exception("Mismatch in events count! Expected " + expected.Length + ", got " + events.Count);
            }

            for (int i = 0; i < expected.Length; i++)
            {
                if (events[i] != expected[i])
                {
                    throw new Exception("Event " + i + " (" + expected[i] + ") mismatched!");
                }
            }

            Console.WriteLine("All tests successful");

            Console.ReadKey();

            server.Shutdown("App exiting");
            client.Shutdown("App exiting");
        }
Esempio n. 24
0
 protected LidgrenTransferPacket BuildTransferPacket(NetBuffer msg)
 {
     try
     {
         //Due to message recycling we cannot trust the internal array of data to be of only the information that should be used for this package.
         //We can trust the indicates size, not the length of .Data, and get a byte[] that represents the sent LidgrenTransferPacket.
         //However, this will incur a GC penalty which may become an issue; more likely to be an issue on clients.
         return(Serializer <GladNetProtobufNetSerializer> .Instance.Deserialize <LidgrenTransferPacket>(msg.ReadBytes(msg.LengthBytes - msg.PositionInBytes)));
     }
     catch (LoggableException e)
     {
         ClassLogger.LogError("Couldn't build lidgren packet: " + e.Message + e.InnerException != null ? e.InnerException.Message : "");
         return(null);
     }
 }
Esempio n. 25
0
 public void DoReceive(NetBuffer buffer)
 {
     byte[] dst = buffer.ReadBytes(buffer.Length);
     m_RecvQueue.Push(dst);
 }
Esempio n. 26
0
        public void UpdateNetwork(GameTime gameTime)
        {
            // Update the server with our status.
            timeSinceLastUpdate += gameTime.ElapsedGameTime.TotalSeconds;
            if (timeSinceLastUpdate > 0.05)
            {
                timeSinceLastUpdate = 0;
                if (CurrentStateType == "Infiniminer.States.MainGameState")
                {
                    propertyBag.SendPlayerUpdate();
                }
            }

            // Recieve messages from the server.
            NetMessageType msgType;

            while (propertyBag.netClient.ReadMessage(msgBuffer, out msgType))
            {
                switch (msgType)
                {
                case NetMessageType.StatusChanged:
                {
                    if (propertyBag.netClient.Status == NetConnectionStatus.Disconnected)
                    {
                        ChangeState("Infiniminer.States.ServerBrowserState");
                    }
                }
                break;

                case NetMessageType.ConnectionApproval:
                    anyPacketsReceived = true;
                    break;

                case NetMessageType.ConnectionRejected:
                {
                    anyPacketsReceived = false;
                    try
                    {
                        string[] reason = msgBuffer.ReadString().Split(";".ToCharArray());
                        if (reason.Length < 2 || reason[0] == "VER")
                        {
                            System.Windows.Forms.MessageBox.Show("Error: client/server version incompability!\r\nServer: " + msgBuffer.ReadString() + "\r\nClient: " + Defines.INFINIMINER_VERSION);
                        }
                        else
                        {
                            System.Windows.Forms.MessageBox.Show("Error: you are banned from this server!");
                        }
                    }
                    catch { }
                    ChangeState("Infiniminer.States.ServerBrowserState");
                }
                break;

                case NetMessageType.Data:
                {
                    try
                    {
                        InfiniminerMessage dataType = (InfiniminerMessage)msgBuffer.ReadByte();
                        switch (dataType)
                        {
                        case InfiniminerMessage.BlockBulkTransfer:
                        {
                            anyPacketsReceived = true;

                            try
                            {
                                //This is either the compression flag or the x coordiante
                                byte isCompressed = msgBuffer.ReadByte();
                                byte x;
                                byte y;

                                //255 was used because it exceeds the map size - of course, bytes won't work anyway if map sizes are allowed to be this big, so this method is a non-issue
                                if (isCompressed == 255)
                                {
                                    var compressed       = msgBuffer.ReadBytes(msgBuffer.LengthBytes - msgBuffer.Position / 8);
                                    var compressedstream = new System.IO.MemoryStream(compressed);
                                    var decompresser     = new System.IO.Compression.GZipStream(compressedstream, System.IO.Compression.CompressionMode.Decompress);

                                    x = (byte)decompresser.ReadByte();
                                    y = (byte)decompresser.ReadByte();
                                    propertyBag.mapLoadProgress[x, y] = true;
                                    for (byte dy = 0; dy < 16; dy++)
                                    {
                                        for (byte z = 0; z < 64; z++)
                                        {
                                            BlockType blockType = (BlockType)decompresser.ReadByte();
                                            if (blockType != BlockType.None)
                                            {
                                                propertyBag.blockEngine.downloadList[x, y + dy, z] = blockType;
                                            }
                                        }
                                    }
                                }
                                else
                                {
                                    x = isCompressed;
                                    y = msgBuffer.ReadByte();
                                    propertyBag.mapLoadProgress[x, y] = true;
                                    for (byte dy = 0; dy < 16; dy++)
                                    {
                                        for (byte z = 0; z < 64; z++)
                                        {
                                            BlockType blockType = (BlockType)msgBuffer.ReadByte();
                                            if (blockType != BlockType.None)
                                            {
                                                propertyBag.blockEngine.downloadList[x, y + dy, z] = blockType;
                                            }
                                        }
                                    }
                                }
                                bool downloadComplete = true;
                                for (x = 0; x < 64; x++)
                                {
                                    for (y = 0; y < 64; y += 16)
                                    {
                                        if (propertyBag.mapLoadProgress[x, y] == false)
                                        {
                                            downloadComplete = false;
                                            break;
                                        }
                                    }
                                }
                                if (downloadComplete)
                                {
                                    ChangeState("Infiniminer.States.TeamSelectionState");
                                    if (!NoSound)
                                    {
                                        MediaPlayer.Stop();
                                    }
                                    propertyBag.blockEngine.DownloadComplete();
                                }
                            }
                            catch (Exception e)
                            {
                                Console.OpenStandardError();
                                Console.Error.WriteLine(e.Message);
                                Console.Error.WriteLine(e.StackTrace);
                                Console.Error.Close();
                            }
                        }
                        break;

                        case InfiniminerMessage.SetBeacon:
                        {
                            Vector3    position = msgBuffer.ReadVector3();
                            string     text     = msgBuffer.ReadString();
                            PlayerTeam team     = (PlayerTeam)msgBuffer.ReadByte();

                            if (text == "")
                            {
                                if (propertyBag.beaconList.ContainsKey(position))
                                {
                                    propertyBag.beaconList.Remove(position);
                                }
                            }
                            else
                            {
                                Beacon newBeacon = new Beacon();
                                newBeacon.ID   = text;
                                newBeacon.Team = team;
                                propertyBag.beaconList.Add(position, newBeacon);
                            }
                        }
                        break;

                        case InfiniminerMessage.TriggerConstructionGunAnimation:
                        {
                            propertyBag.constructionGunAnimation = msgBuffer.ReadFloat();
                            if (propertyBag.constructionGunAnimation <= -0.1)
                            {
                                propertyBag.PlaySound(InfiniminerSound.RadarSwitch);
                            }
                        }
                        break;

                        case InfiniminerMessage.ResourceUpdate:
                        {
                            // ore, cash, weight, max ore, max weight, team ore, red cash, blue cash, all uint
                            propertyBag.playerOre       = msgBuffer.ReadUInt32();
                            propertyBag.playerCash      = msgBuffer.ReadUInt32();
                            propertyBag.playerWeight    = msgBuffer.ReadUInt32();
                            propertyBag.playerOreMax    = msgBuffer.ReadUInt32();
                            propertyBag.playerWeightMax = msgBuffer.ReadUInt32();
                            propertyBag.teamOre         = msgBuffer.ReadUInt32();
                            propertyBag.teamRedCash     = msgBuffer.ReadUInt32();
                            propertyBag.teamBlueCash    = msgBuffer.ReadUInt32();
                        }
                        break;

                        case InfiniminerMessage.BlockSet:
                        {
                            // x, y, z, type, all bytes
                            byte      x         = msgBuffer.ReadByte();
                            byte      y         = msgBuffer.ReadByte();
                            byte      z         = msgBuffer.ReadByte();
                            BlockType blockType = (BlockType)msgBuffer.ReadByte();
                            if (blockType == BlockType.None)
                            {
                                if (propertyBag.blockEngine.BlockAtPoint(new Vector3(x, y, z)) != BlockType.None)
                                {
                                    propertyBag.blockEngine.RemoveBlock(x, y, z);
                                }
                            }
                            else
                            {
                                if (propertyBag.blockEngine.BlockAtPoint(new Vector3(x, y, z)) != BlockType.None)
                                {
                                    propertyBag.blockEngine.RemoveBlock(x, y, z);
                                }
                                propertyBag.blockEngine.AddBlock(x, y, z, blockType);
                                CheckForStandingInLava();
                            }
                        }
                        break;

                        case InfiniminerMessage.TriggerExplosion:
                        {
                            Vector3 blockPos = msgBuffer.ReadVector3();

                            // Play the explosion sound.
                            propertyBag.PlaySound(InfiniminerSound.Explosion, blockPos);

                            // Create some particles.
                            propertyBag.particleEngine.CreateExplosionDebris(blockPos);

                            // Figure out what the effect is.
                            float distFromExplosive = (blockPos + 0.5f * Vector3.One - propertyBag.playerPosition).Length();
                            if (distFromExplosive < 3)
                            {
                                propertyBag.KillPlayer(Defines.deathByExpl);                //"WAS KILLED IN AN EXPLOSION!");
                            }
                            else if (distFromExplosive < 8)
                            {
                                // If we're not in explosion mode, turn it on with the minimum ammount of shakiness.
                                if (propertyBag.screenEffect != ScreenEffect.Explosion)
                                {
                                    propertyBag.screenEffect        = ScreenEffect.Explosion;
                                    propertyBag.screenEffectCounter = 2;
                                }
                                // If this bomb would result in a bigger shake, use its value.
                                propertyBag.screenEffectCounter = Math.Min(propertyBag.screenEffectCounter, (distFromExplosive - 2) / 5);
                            }
                        }
                        break;

                        case InfiniminerMessage.PlayerSetTeam:
                        {
                            uint playerId = msgBuffer.ReadUInt32();
                            if (propertyBag.playerList.ContainsKey(playerId))
                            {
                                Player player = propertyBag.playerList[playerId];
                                player.Team = (PlayerTeam)msgBuffer.ReadByte();
                            }
                        }
                        break;

                        case InfiniminerMessage.PlayerJoined:
                        {
                            uint   playerId    = msgBuffer.ReadUInt32();
                            string playerName  = msgBuffer.ReadString();
                            bool   thisIsMe    = msgBuffer.ReadBoolean();
                            bool   playerAlive = msgBuffer.ReadBoolean();
                            propertyBag.playerList[playerId]            = new Player(null, (Game)this);
                            propertyBag.playerList[playerId].Handle     = playerName;
                            propertyBag.playerList[playerId].ID         = playerId;
                            propertyBag.playerList[playerId].Alive      = playerAlive;
                            propertyBag.playerList[playerId].AltColours = customColours;
                            propertyBag.playerList[playerId].redTeam    = red;
                            propertyBag.playerList[playerId].blueTeam   = blue;
                            if (thisIsMe)
                            {
                                propertyBag.playerMyId = playerId;
                            }
                        }
                        break;

                        case InfiniminerMessage.PlayerLeft:
                        {
                            uint playerId = msgBuffer.ReadUInt32();
                            if (propertyBag.playerList.ContainsKey(playerId))
                            {
                                propertyBag.playerList.Remove(playerId);
                            }
                        }
                        break;

                        case InfiniminerMessage.PlayerDead:
                        {
                            uint playerId = msgBuffer.ReadUInt32();
                            if (propertyBag.playerList.ContainsKey(playerId))
                            {
                                Player player = propertyBag.playerList[playerId];
                                player.Alive = false;
                                propertyBag.particleEngine.CreateBloodSplatter(player.Position, player.Team == PlayerTeam.Red ? Color.Red : Color.Blue);
                                if (playerId != propertyBag.playerMyId)
                                {
                                    propertyBag.PlaySound(InfiniminerSound.Death, player.Position);
                                }
                            }
                        }
                        break;

                        case InfiniminerMessage.PlayerAlive:
                        {
                            uint playerId = msgBuffer.ReadUInt32();
                            if (propertyBag.playerList.ContainsKey(playerId))
                            {
                                Player player = propertyBag.playerList[playerId];
                                player.Alive = true;
                            }
                        }
                        break;

                        case InfiniminerMessage.PlayerUpdate:
                        {
                            uint playerId = msgBuffer.ReadUInt32();
                            if (propertyBag.playerList.ContainsKey(playerId))
                            {
                                Player player = propertyBag.playerList[playerId];
                                player.UpdatePosition(msgBuffer.ReadVector3(), gameTime.TotalGameTime.TotalSeconds);
                                player.Heading   = msgBuffer.ReadVector3();
                                player.Tool      = (PlayerTools)msgBuffer.ReadByte();
                                player.UsingTool = msgBuffer.ReadBoolean();
                                player.Score     = (uint)(msgBuffer.ReadUInt16() * 100);
                            }
                        }
                        break;

                        case InfiniminerMessage.GameOver:
                        {
                            propertyBag.teamWinners = (PlayerTeam)msgBuffer.ReadByte();
                        }
                        break;

                        case InfiniminerMessage.ChatMessage:
                        {
                            ChatMessageType chatType   = (ChatMessageType)msgBuffer.ReadByte();
                            string          chatString = Defines.Sanitize(msgBuffer.ReadString());
                            //Time to break it up into multiple lines
                            propertyBag.addChatMessage(chatString, chatType, 10);
                        }
                        break;

                        case InfiniminerMessage.PlayerPing:
                        {
                            uint playerId = (uint)msgBuffer.ReadInt32();
                            if (propertyBag.playerList.ContainsKey(playerId))
                            {
                                if (propertyBag.playerList[playerId].Team == propertyBag.playerTeam)
                                {
                                    propertyBag.playerList[playerId].Ping = 1;
                                    propertyBag.PlaySound(InfiniminerSound.Ping);
                                }
                            }
                        }
                        break;

                        case InfiniminerMessage.PlaySound:
                        {
                            InfiniminerSound sound       = (InfiniminerSound)msgBuffer.ReadByte();
                            bool             hasPosition = msgBuffer.ReadBoolean();
                            if (hasPosition)
                            {
                                Vector3 soundPosition = msgBuffer.ReadVector3();
                                propertyBag.PlaySound(sound, soundPosition);
                            }
                            else
                            {
                                propertyBag.PlaySound(sound);
                            }
                        }
                        break;
                        }
                    }
                    catch { }         //Error in a received message
                }
                break;
                }
            }

            // Make sure our network thread actually gets to run.
            Thread.Sleep(1);
        }
Esempio n. 27
0
 /// <inheritdoc />
 public void ReadFromBuffer(NetBuffer buffer)
 {
     Id       = new Guid(buffer.ReadBytes(16));
     Nickname = buffer.ReadString();
 }
        public Password(NetBuffer buffer)
        {
            uint length = buffer.ReadVariableUInt32();

            hash = buffer.ReadBytes((int)length);
        }
Esempio n. 29
0
 public override int Read(byte[] buffer, int offset, int count)
 {
     Buffer.ReadBytes(buffer, offset, count);
     return(count);
 }
Esempio n. 30
0
    public static void UnpackFrom(this Guid inGuid, NetBuffer inBuffer, ref Guid inDestination)
    {
        byte[] guidBytes = inBuffer.ReadBytes(GUID_NUM_BYTES);

        inDestination = new Guid(guidBytes);
    }