ReadInt32() public method

Reads a 32 bit signed integer written using Write(Int32)
public ReadInt32 ( ) : Int32
return System.Int32
示例#1
0
 public void Read(NetBuffer im)
 {
     MessagePacketId = im.ReadInt64();
     Number          = im.ReadInt32();
     int length      = im.ReadInt32();
     if (length != 0)
     {
         Bytes = im.ReadBytes(length);
     }
 }
示例#2
0
 public override void Read(NetBuffer im)
 {
     base.Read(im);
     int c = im.ReadInt32();
     for(int i = 0; i < c; ++i)
     {
         int id = im.ReadInt32();
         FollowerId.Add(id);
     }
 }
示例#3
0
 public override void Read(NetBuffer im)
 {
     base.Read(im);
     int c = im.ReadInt32();
     for(int i = 0; i < c; ++i)
     {
         int objId = im.ReadInt32();
         int folId = im.ReadInt32();
         Followers.Add(new KeyValuePair<int, int>(objId, folId));
     }
 }
示例#4
0
        bool ClientCommand(client_t cl, NetBuffer msg)
        {
            int seq = msg.ReadInt32();
            string s = msg.ReadString();

            // see if we have already executed it
            if (cl.lastClientCommand >= seq)
                return true;

            Common.Instance.WriteLine("ClientCommand: {0}[s{1}]: {2}", cl.name, seq, s);

            // drop the connection if we have somehow lost commands
            if (seq > cl.lastClientCommand + 1)
            {
                Common.Instance.WriteLine("Client {0} lost {1} clientCommands", cl.name, seq-cl.lastClientCommand+1);
                DropClient(cl, "Lost reliable commands");
                return false;
            }

            // don't allow another command for one second
            cl.nextReliableTime = (int)time + 1000;

            ExecuteClientCommand(cl, s);
            cl.lastClientCommand = seq;
            cl.lastClientCommandString = s;
            return true;    // continue procesing
        }
示例#5
0
 public override void Read(NetBuffer im)
 {
     base.Read(im);
     int c = im.ReadInt32();
     for(int i = 0; i < c; ++i)
     {
         var objid       = im.ReadInt32();
         var followerid  = im.ReadInt32();
         FollowerList.Add(new KeyValuePair<int, int>(objid, followerid));
     }
     c = im.ReadInt32();
     for (int i = 0; i < c; ++i)
     {
         var follower = im.ReadInt32();
         FightFollowerList.Add(follower);
     }
 }
示例#6
0
        /*
        =====================
        CL_ParseCommandString

        Command strings are just saved off until cgame asks for them
        when it transitions a snapshot
        =====================
        */
        void ParseCommandString(NetBuffer buf)
        {
            int seq = buf.ReadInt32();
            string s = buf.ReadString();

            // see if we have already executed stored it off
            if (clc.serverCommandSequence >= seq)
                return;

            clc.serverCommandSequence = seq;
            int index = seq & 63;
            clc.serverCommands[index] = s;
        }
示例#7
0
        public void Read(NetBuffer im)
        {
            if (Plugins == null)
            {
                Plugins = new List<string>();
            }

            int count = im.ReadInt32();
            for(int i = 0; i < count; ++i)
            {
                var plugin = im.ReadString();
                Plugins.Add(plugin);
            }
        }
示例#8
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);
     }
 }
示例#9
0
 public void Read(NetBuffer im)
 {
     MetaData    = im.ReadString();
     int l       = im.ReadInt32();
     Data        = im.ReadBytes(l);
 }
示例#10
0
        void ParseGameState(NetBuffer msg)
        {
            clc.connectPacketCount = 0;
            // wipe local client state
            ClearState();
            // a gamestate always marks a server command sequence
            clc.serverCommandSequence = msg.ReadInt32();
            // parse all the configstrings and baselines
            while (true)
            {
                int cmd = msg.ReadByte();

                if (cmd == (int)svc_ops_e.svc_EOF)
                    break;

                if (cmd == (int)svc_ops_e.svc_configstring)
                {
                    int index = msg.ReadInt16();
                    string s = msg.ReadString();
                    cl.gamestate.data.Add(index, s);
                }
                else if (cmd == (int)svc_ops_e.svc_baseline)
                {
                    int newnum = msg.ReadInt32();
                    if (newnum < 0 || newnum >= 1024)
                    {
                        Common.Instance.Error("ParseGameState: Baseline number out of range: " + newnum);
                    }
                    Common.entityState_t nullstate = new Common.entityState_t();
                    Net.Instance.MSG_ReadDeltaEntity(msg, ref nullstate, ref cl.entityBaselines[newnum], newnum);
                }
                else
                {
                    Common.Instance.Error("ParseGameState: bad command byte");
                }
            }

            clc.clientNum = msg.ReadInt32();

            // parse useful values out of CS_SERVERINFO
            //ParseServerInfo();

            // parse serverId and other cvars
            SystemInfoChanged();

            InitDownloads();
        }
示例#11
0
        /*
        ================
        CL_ParseSnapshot

        If the snapshot is parsed properly, it will be copied to
        cl.snap and saved in cl.snapshots[].  If the snapshot is invalid
        for any reason, no changes to the state will be made at all.
        ================
        */
        void ParseSnapshot(NetBuffer msg)
        {
            // read in the new snapshot to a temporary buffer
            // we will only copy to cl.snap if it is valid
            clSnapshot_t newsnap = new clSnapshot_t();
            clSnapshot_t old;

            // we will have read any new server commands in this
            // message before we got to svc_snapshot
            newsnap.ServerCommandNum = clc.serverCommandSequence;
            newsnap.serverTime = msg.ReadInt32();
            newsnap.messageNum = clc.serverMessageSequence;

            int deltaNum = msg.ReadByte();

            if (deltaNum <= 0)
            {
                newsnap.deltaNum = -1;
            }
            else
                newsnap.deltaNum = newsnap.messageNum - deltaNum;
            newsnap.snapFlags = msg.ReadByte();

            // If the frame is delta compressed from data that we
            // no longer have available, we must suck up the rest of
            // the frame, but not use it, then ask for a non-compressed
            // message
            if (newsnap.deltaNum <= 0)
            {
                newsnap.valid = true;   // uncompressed frame
                old = null;
            }
            else
            {
                old = cl.snapshots[newsnap.deltaNum & 31];
                if (!old.valid)
                {
                    // should never happen
                    Common.Instance.WriteLine("ParseSnapshot: Delta from invalid frame (not supposed to happen!).");
                }
                else if (old.messageNum != newsnap.deltaNum)
                {
                    // The frame that the server did the delta from
                    // is too old, so we can't reconstruct it properly.
                    Common.Instance.WriteLine("ParseSnapshot: Delta frame too old.");
                }
                else if (cl.parseEntitiesNum - old.parseEntitiesNum > 2048 - 128)
                {
                    Common.Instance.WriteLine("ParseSnapshot: Delta parseEntitiesNum too old");
                }
                else
                    newsnap.valid = true;   // valid delta parse
            }

            // read areamask
            int len = msg.ReadByte();
            newsnap.areamask = msg.ReadBytes(32);
            // read playerinfo
            if (old != null)
            {
                Net.ReadDeltaPlayerstate(msg, old.ps, newsnap.ps);
            }
            else
                Net.ReadDeltaPlayerstate(msg, null, newsnap.ps);

            // read packet entities
            ParsePacketEntities(msg, old, newsnap);

            // if not valid, dump the entire thing now that it has
            // been properly read
            if (!newsnap.valid)
                return;

            // clear the valid flags of any snapshots between the last
            // received and this one, so if there was a dropped packet
            // it won't look like something valid to delta from next
            // time we wrap around in the buffer
            int oldMessageNum = cl.snap.messageNum + 1;
            if (newsnap.messageNum - oldMessageNum >= 32)
            {
                oldMessageNum = newsnap.messageNum - 31;
            }
            for (; oldMessageNum < newsnap.messageNum; oldMessageNum++ )
            {
                cl.snapshots[oldMessageNum & 31].valid = false;
            }

            // copy to the current good spot
            cl.snap = newsnap;
            cl.snap.ping = 999;
            // calculate ping time
            for (int i = 0; i < 32; i++)
            {
                int packetNum = (clc.netchan.outgoingSequence - 1 - i) & 31;
                if (cl.snap.ps.commandTime >= cl.outPackets[packetNum].p_serverTime)
                {
                    cl.snap.ping = realtime - cl.outPackets[packetNum].p_realtime;
                    break;
                }
            }

            // save the frame off in the backup array for later delta comparisons
            cl.snapshots[cl.snap.messageNum & 31] = cl.snap;

            //Common.Instance.WriteLine("   Snapshot:{0} delta:{1} ping:{2}", cl.snap.messageNum, cl.snap.deltaNum, cl.snap.ping);
            cl.newSnapshots = true;
        }
示例#12
0
        void ParsePacketEntities(NetBuffer msg, clSnapshot_t oldframe, clSnapshot_t newframe)
        {
            newframe.parseEntitiesNum = cl.parseEntitiesNum;
            newframe.numEntities = 0;

            // delta from the entities present in oldframe
            int oldindex = 0, oldnum = 0;
            Common.entityState_t oldstate = null;
            if (oldframe == null)
                oldnum = 99999;
            else
            {
                if (oldnum >= oldframe.numEntities)
                    oldnum = 99999;
                else
                {
                    oldstate = cl.parseEntities[(oldframe.parseEntitiesNum + oldindex) & 2047];
                    oldnum = oldstate.number;
                }
            }

            while (true)
            {
                // read the entity index number
                int newnum = msg.ReadInt32();

                if (newnum == 1023)
                    break;

                while (oldnum < newnum)
                {
                    // one or more entities from the old packet are unchanged
                    DeltaEntity(msg, newframe, oldnum, oldstate, true);
                    oldindex++;

                    if (oldindex >= oldframe.numEntities)
                        oldnum = 99999;
                    else
                    {
                        oldstate = cl.parseEntities[(oldframe.parseEntitiesNum + oldindex) & 2047];
                        oldnum = oldstate.number;
                    }
                }
                if (oldnum == newnum)
                {
                    // delta from previous state
                    DeltaEntity(msg, newframe, newnum, oldstate, false);

                    oldindex++;

                    if (oldindex >= oldframe.numEntities)
                        oldnum = 99999;
                    else
                    {
                        oldstate = cl.parseEntities[(oldframe.parseEntitiesNum + oldindex) & 2047];
                        oldnum = oldstate.number;
                    }
                    continue;
                }

                if (oldnum > newnum)
                {
                    // delta from baseline
                    DeltaEntity(msg, newframe, newnum, cl.entityBaselines[newnum], false);
                    continue;
                }
            }

            // any remaining entities in the old frame are copied over
            while (oldnum != 99999)
            {
                // one or more entities from the old packet are unchanged
                DeltaEntity(msg, newframe, oldnum, oldstate, true);

                oldindex++;

                if (oldindex >= oldframe.numEntities)
                    oldnum = 99999;
                else
                {
                    oldstate = cl.parseEntities[(oldframe.parseEntitiesNum + oldindex) & 2047];
                    oldnum = oldstate.number;
                }
            }
        }
示例#13
0
 public void Read(NetBuffer im)
 {
     UniqueIdentifier    = im.ReadInt64();
     TargetSize          = im.ReadInt32();
 }
示例#14
0
 public Message( NetBuffer buffer, NetConnection sender)
 {
     Sender = sender;
     Data = buffer;
     Name = Data.ReadInt32();
 }
示例#15
0
文件: Input.cs 项目: maesse/CubeHags
 int MSG_ReadDeltaKey(NetBuffer msg, int oldV, int bits)
 {
     if (msg.ReadBoolean())
     {
         return (msg.ReadInt32(bits));
     }
     return oldV;
 }
示例#16
0
文件: Input.cs 项目: maesse/CubeHags
        public UserCommand MSG_ReadDeltaUsercmdKey(NetBuffer msg, ref  UserCommand from)
        {
            UserCommand to = new UserCommand();
            if (msg.ReadBoolean())
                to.serverTime = from.serverTime + (int)msg.ReadUInt32(8);
            else
                to.serverTime = msg.ReadInt32();
            if (msg.ReadBoolean())
            {
                to.anglex = (int)MSG_ReadDeltaKey(msg, (uint)from.anglex, 16);
                to.angley = (int)MSG_ReadDeltaKey(msg, (uint)from.angley, 16);
                to.anglez = (int)MSG_ReadDeltaKey(msg, (uint)from.anglez, 16);
                to.forwardmove = (short)MSG_ReadDeltaKey(msg, from.forwardmove, 16);
                to.rightmove = (short)MSG_ReadDeltaKey(msg, from.rightmove, 16);
                to.upmove = (short)MSG_ReadDeltaKey(msg, from.upmove, 16);
                to.buttons = MSG_ReadDeltaKey(msg,  from.buttons, 16);
                to.weapon = (byte)MSG_ReadDeltaKey(msg, from.weapon, 8);
            }
            else
            {
                to.anglex = from.anglex;
                to.angley = from.angley;
                to.anglez = from.anglez;
                to.forwardmove = from.forwardmove;
                to.rightmove = from.rightmove;
                to.upmove = from.upmove;
                to.buttons = from.buttons;
                to.weapon = from.weapon;
            }

            return to;
        }
 /// <summary>
 /// Read a Point
 /// </summary>
 public static Point ReadPoint(this NetBuffer message)
 {
     return(new Point(message.ReadInt32(), message.ReadInt32()));
 }
        private void ReadFieldState(NetBuffer msg, Field field)
        {
            int bitsForPlayerIndex = NetUtility.BitsToHoldUInt((uint)(field.GetPlayers().GetCount() - 1));

            FieldCellSlot[] slots = field.GetCells().slots;
            for (int i = 0; i < slots.Length; ++i)
            {
                FieldCellSlot slot = slots[i];

                bool hasStaticCell = msg.ReadBoolean();
                if (hasStaticCell)
                {
                    byte type = msg.ReadByte(BITS_FOR_STATIC_CELL);
                    switch (type)
                    {
                        case CELL_BRICK:
                        {
                            Debug.Assert(slot.ContainsBrick());
                            break;
                        }

                        case CELL_POWERUP:
                        {
                            int powerup = msg.ReadInt32(BITS_FOR_POWERUP);
                            if (slot.staticCell == null)
                            {
                                field.AddCell(new PowerupCell(powerup, slot.cx, slot.cy));
                            }
                            else if (!slot.staticCell.IsPowerup())
                            {
                                field.RemoveCell(slot.staticCell);
                                field.AddCell(new PowerupCell(powerup, slot.cx, slot.cy));
                            }
                            break;
                        }

                        case CELL_FLAME:
                        {
                            int playerIndex = msg.ReadInt32(bitsForPlayerIndex);
                            if (slot.staticCell == null)
                            {
                                Player player = field.GetPlayers().Get(playerIndex);
                                field.AddCell(new FlameCell(player, slot.cx, slot.cy));
                            }
                            else if (!slot.staticCell.IsFlame())
                            {
                                Player player = field.GetPlayers().Get(playerIndex);
                                field.RemoveCell(slot.staticCell);
                                field.AddCell(new FlameCell(player, slot.cx, slot.cy));
                            }
                            break;
                        }
                    }
                }
                else if (slot.staticCell != null && !slot.staticCell.IsSolid())
                {
                    field.RemoveCell(slot.staticCell);
                }
            }
        }
        /* the server reads data from a client */
        protected ClientPacket ReadClientPacket(NetBuffer msg)
        {
            ClientPacket packet;
            packet.id = msg.ReadInt32();
            packet.lastAckServerPacketId = msg.ReadInt32();
            packet.actions = msg.ReadInt32((int)PlayerAction.Count);

            return packet;
        }
示例#20
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");
		}
示例#21
0
        protected override NetBuffer ProcessInboundMessage(NetBuffer message)
        {
            switch(cryptoState)
            {
                case CryptoHostState.Connected:
                    {
                        int code = message.ReadInt32();
                        if (code == RSA_KEY_MESSAGE)
                        {
                            XmlSerializer s = new XmlSerializer(typeof(RSAParameters));
                            string b = message.ReadString();
                            StringReader reader = new StringReader(b);
                            RSAKey = (RSAParameters)s.Deserialize(reader);
                            RSA = new RSACryptoServiceProvider();
                            RSA.ImportParameters(RSAKey);

                            NetBuffer msg = new NetBuffer();
                            msg.Write((Int32)CRYPTO_SECRET_MESSAGE);

                            byte[] secret = RSA.Encrypt(MakeSecret(),false);
                            msg.Write((Int32)secret.Length);
                            msg.Write(secret);
                            client.SendMessage(msg,NetChannel.ReliableInOrder1);
                            cryptoState = CryptoHostState.SentSecret;
                        }
                        else
                        {
                            cryptoState = CryptoHostState.Invalid;
                            client.Disconnect("Bad Crypto");
                        }
                    }
                    return null;

                case CryptoHostState.SentSecret:
                    {
                        int code = message.ReadInt32();
                        if (code == CRYPTO_SECRET_VERIFY)
                        {
                            // set em as real and let the base class call any events it needs to
                            string verify = new UTF8Encoding().GetString(DecryptBuffer(message.ReadBytes(message.ReadInt32())));

                            NetBuffer b = new NetBuffer();
                            b.Write(CRYPTO_SECRET_VERIFY);
                            byte[] cryptoBuffer = EncryptBuffer(new UTF8Encoding().GetBytes(verify));
                            b.Write(cryptoBuffer.Length);
                            b.Write(cryptoBuffer);
                            client.SendMessage(b, NetChannel.ReliableInOrder1);

                            cryptoState = CryptoHostState.SentVerify;
                        }
                        else
                        {
                            cryptoState = CryptoHostState.Invalid;
                            client.Disconnect("Bad Crypto");
                        }
                    }
                   return null;

                case CryptoHostState.SentVerify:
                    {
                        int code = message.ReadInt32();
                        if (code == CRYPTO_ACCEPT)
                        {
                            cryptoState = CryptoHostState.Authenticated;
                            base.Connected(message);
                        }
                        else
                        {
                            cryptoState = CryptoHostState.Invalid;
                            client.Disconnect("Bad Crypto");
                        }
                    }
                    return null;

                case CryptoHostState.Authenticated:
                    return new NetBuffer(DecryptBuffer(message.ReadBytes(message.LengthBytes)));
            }
            return message;
        }
示例#22
0
文件: Net.cs 项目: maesse/CubeHags
        public static void ReadDeltaPlayerstate(NetBuffer msg, Common.PlayerState from, Common.PlayerState to)
        {
            int startoffset = msg.Position;
            if (from == null)
                from = new Common.PlayerState();

            to.commandTime = msg.ReadBoolean() ? msg.ReadInt32() : from.commandTime;
            to.pm_type = msg.ReadBoolean() ? (Common.PMType)msg.ReadInt32() : from.pm_type;
            to.pm_flags = msg.ReadBoolean() ? (client.PMFlags)msg.ReadInt32() : from.pm_flags;
            to.pm_time = msg.ReadBoolean() ? msg.ReadInt32() : from.pm_time;
            to.origin.X = msg.ReadBoolean() ? msg.ReadFloat() : from.origin.X;
            to.origin.Y = msg.ReadBoolean() ? msg.ReadFloat() : from.origin.Y;
            to.origin.Z = msg.ReadBoolean() ? msg.ReadFloat() : from.origin.Z;
            to.velocity.X = msg.ReadBoolean() ? msg.ReadFloat() : from.velocity.X;
            to.velocity.Y = msg.ReadBoolean() ? msg.ReadFloat() : from.velocity.Y;
            to.velocity.Z = msg.ReadBoolean() ? msg.ReadFloat() : from.velocity.Z;
            to.weaponTime = msg.ReadBoolean() ? msg.ReadInt32() : from.weaponTime;
            to.gravity = msg.ReadBoolean() ? msg.ReadInt32() : from.gravity;
            to.delta_angles[0] = msg.ReadBoolean() ? msg.ReadInt32() : from.delta_angles[0];
            to.delta_angles[1] = msg.ReadBoolean() ? msg.ReadInt32() : from.delta_angles[1];
            to.delta_angles[2] = msg.ReadBoolean() ? msg.ReadInt32() : from.delta_angles[2];
            to.groundEntityNum = msg.ReadBoolean() ? msg.ReadInt32() : from.groundEntityNum;
            to.movementDir = msg.ReadBoolean() ? msg.ReadInt32() : from.movementDir;
            to.ladderNormal.X = msg.ReadBoolean() ? msg.ReadFloat() : from.ladderNormal.X;
            to.ladderNormal.Y = msg.ReadBoolean() ? msg.ReadFloat() : from.ladderNormal.Y;
            to.ladderNormal.Z = msg.ReadBoolean() ? msg.ReadFloat() : from.ladderNormal.Z;
            to.speed = msg.ReadBoolean() ? msg.ReadInt32() : from.speed;
            to.eFlags = msg.ReadBoolean() ? (Common.EntityFlags)Enum.Parse(typeof(Common.EntityFlags), ""+msg.ReadInt32()) : from.eFlags;
            to.eventSequence = msg.ReadBoolean() ? msg.ReadInt32() : from.eventSequence;
            to.events[0] = msg.ReadBoolean() ? msg.ReadInt32() : from.events[0];
            to.events[1] = msg.ReadBoolean() ? msg.ReadInt32() : from.events[1];
            to.eventParms[0] = msg.ReadBoolean() ? msg.ReadInt32() : from.eventParms[0];
            to.eventParms[1] = msg.ReadBoolean() ? msg.ReadInt32() : from.eventParms[1];
            to.externalEvent = msg.ReadBoolean() ? msg.ReadInt32() : from.externalEvent;
            to.externalEventParm = msg.ReadBoolean() ? msg.ReadInt32() : from.externalEventParm;
            to.externalEventTime = msg.ReadBoolean() ? msg.ReadInt32() : from.externalEventTime;
            to.clientNum = msg.ReadBoolean() ? msg.ReadInt32() : from.clientNum;
            to.viewangles.X = msg.ReadBoolean() ? msg.ReadFloat() : from.viewangles.X;
            to.viewangles.Y = msg.ReadBoolean() ? msg.ReadFloat() : from.viewangles.Y;
            to.viewangles.Z = msg.ReadBoolean() ? msg.ReadFloat() : from.viewangles.Z;
            to.viewheight = msg.ReadBoolean() ? msg.ReadInt32() : from.viewheight;
            //if (to.viewheight == 16)
            //{
            //    int test = 2;
            //}
            to.generic1 = msg.ReadBoolean() ? msg.ReadInt32() : from.generic1;
            to.bobCycle = msg.ReadBoolean() ? msg.ReadInt32() : from.bobCycle;

            to.Ducked = msg.ReadBoolean() ? msg.ReadBoolean() : from.Ducked;
            to.Ducking = msg.ReadBoolean() ? msg.ReadBoolean() : from.Ducking;
            to.DuckTime = msg.ReadBoolean() ? msg.ReadInt32() : from.DuckTime;
            to.OldButtons = msg.ReadBoolean() ? msg.ReadInt32() : from.OldButtons;

            // Got diff arrays

            int msgMiddle = 99999;
            if (msg.ReadBoolean())
            {
                if (msg.ReadBoolean())
                {
                    // stat
                    int statbits = msg.ReadInt32();
                    for (int i = 0; i < 16; i++)
                    {
                        if ((statbits & (1 << i)) == (1 << i))
                        {
                            to.stats[i] = msg.ReadInt16();
                        }
                        else
                            to.stats[i] = from.stats[i];
                    }
                }
                else
                    to.stats = from.stats;
                msgMiddle = msg.Position;
                if (msg.ReadBoolean())
                {
                    // pers
                    int persbits = msg.ReadInt32();
                    for (int i = 0; i < 16; i++)
                    {
                        if ((persbits & (1 << i)) == (1 << i))
                        {
                            to.persistant[i] = msg.ReadInt16();
                        }
                        else
                            to.persistant[i] = from.persistant[i];
                    }
                }
                else
                    to.persistant = from.persistant;
            }
            else
            {
                to.stats = from.stats;
                to.persistant = from.persistant;
            }

            //System.Console.WriteLine("Read {0}bits snapshot, {1} middle", msg.Position - startoffset, msgMiddle - startoffset);
        }
示例#23
0
        protected override NetBuffer ProcessInboundMessage(NetConnection from, NetBuffer message)
        {
            CryptoHostConnection connection;
            if (CryptoClients.ContainsKey(from))
                connection = CryptoClients[from];
            else
                return message;

            int code = -1;

            switch (connection.state)
            {
                case CryptoHostState.Authenticated:
                    return DecryptMessage(connection, message);

                case CryptoHostState.Invalid:
                    return null;

                case CryptoHostState.InitalConnect:
                    {
                        // should be the response with a random key encoded with the shit
                        code = message.ReadInt32();
                        if (code == CRYPTO_SECRET_MESSAGE)
                        {
                            connection.state = CryptoHostState.GotSecret;
                            connection.SetSecret(RSA.Decrypt(message.ReadBytes(message.ReadInt32()),false));
                            connection.secretVerifyString = new Random().Next().ToString();

                            // crypto the random string with the secret and send it back
                            NetBuffer b = new NetBuffer();
                            b.Write(CRYPTO_SECRET_VERIFY);
                            byte[] cryptoBuffer = connection.EncryptBuffer(new UTF8Encoding().GetBytes(connection.secretVerifyString));
                            b.Write(cryptoBuffer.Length);
                            b.Write(cryptoBuffer);
                            server.SendMessage(b, from, NetChannel.ReliableInOrder1);
                        }
                        else
                        {
                            NetBuffer errorBuffer = new NetBuffer();
                            errorBuffer.Write(CRYPTO_DENY);
                            errorBuffer.Write("Invalid Secret");
                            server.SendMessage(errorBuffer, from, NetChannel.ReliableInOrder1);
                            from.Disconnect("CryptoError", 1);
                            connection.state = CryptoHostState.Invalid;
                        }
                        return null;
                    }

                case CryptoHostState.GotSecret:
                    {
                        // should be the response with the properly encrypted sample
                        code = message.ReadInt32();
                        if (code == CRYPTO_SECRET_VERIFY)
                        {
                            // set em as real and let the base class call any events it needs to
                            string verify = new UTF8Encoding().GetString(connection.DecryptBuffer(message.ReadBytes(message.ReadInt32())));

                            if (verify == connection.secretVerifyString)
                            {
                                connection.state = CryptoHostState.Authenticated;
                                NetBuffer b = new NetBuffer();
                                b.Write(CRYPTO_ACCEPT);
                                server.SendMessage(b, from, NetChannel.ReliableInOrder1);
                                base.UserConnected(from);
                                return null;
                            }
                        }

                        NetBuffer errorBuffer = new NetBuffer();
                        errorBuffer.Write(CRYPTO_DENY);
                        errorBuffer.Write("Invalid Verify");
                        server.SendMessage(errorBuffer, from, NetChannel.ReliableInOrder1);
                        from.Disconnect("CryptoError", 1);
                        connection.state = CryptoHostState.Invalid;
                        return null;
                    }
            }
            return message;
        }
示例#24
0
文件: Net.cs 项目: maesse/CubeHags
        /*
        ==================
        MSG_ReadDeltaEntity

        The entity number has already been read from the message, which
        is how the from state is identified.

        If the delta removes the entity, entityState_t->number will be set to MAX_GENTITIES-1

        Can go from either a baseline or a previous packet_entity
        ==================
        */
        public void MSG_ReadDeltaEntity(NetBuffer msg, ref Common.entityState_t from, ref Common.entityState_t to, int number)
        {
            int startBit = msg.Position-32;
            if (number < 0 || number >= 1024)
            {
                Common.Instance.Error("ReadDeltaEntity: number < 0 || number >= 1024");
            }

            // Check for remove
            if (msg.ReadBoolean())
            {
                to = new Common.entityState_t();
                to.number = 1023;
                Common.Instance.WriteLine("Removed entity: {0}", number);
                return;
            }

            // Check for no delta
            if (!msg.ReadBoolean())
            {
                to = from;
                to.number = number;
                return;
            }

            to.number = number;
            int dataStart = msg.Position;
            to.eType = msg.ReadBoolean() ? msg.ReadInt32() : from.eType;
            to.eFlags = msg.ReadBoolean() ? (Common.EntityFlags)msg.ReadInt32() : from.eFlags;
            int middle = msg.Position;
            to.pos.trBase.X = msg.ReadBoolean() ? msg.ReadFloat() : from.pos.trBase.X;
            to.pos.trBase.Y = msg.ReadBoolean() ? msg.ReadFloat() : from.pos.trBase.Y;
            to.pos.trBase.Z = msg.ReadBoolean() ? msg.ReadFloat() : from.pos.trBase.Z;
            to.pos.trDelta.X = msg.ReadBoolean() ? msg.ReadFloat() : from.pos.trDelta.X;
            to.pos.trDelta.Y = msg.ReadBoolean() ? msg.ReadFloat() : from.pos.trDelta.Y;
            to.pos.trDelta.Z = msg.ReadBoolean() ? msg.ReadFloat() : from.pos.trDelta.Z;
            to.pos.trDuration = msg.ReadBoolean() ? msg.ReadInt32() : from.pos.trDuration;
            to.pos.trTime = msg.ReadBoolean() ? msg.ReadInt32() : from.pos.trTime;
            to.pos.trType = msg.ReadBoolean() ? (Common.trType_t)msg.ReadInt32() : from.pos.trType;

            to.apos.trBase.X = msg.ReadBoolean() ? msg.ReadFloat() : from.apos.trBase.X;
            to.apos.trBase.Y = msg.ReadBoolean() ? msg.ReadFloat() : from.apos.trBase.Y;
            to.apos.trBase.Z = msg.ReadBoolean() ? msg.ReadFloat() : from.apos.trBase.Z;
            to.apos.trDelta.X = msg.ReadBoolean() ? msg.ReadFloat() : from.apos.trDelta.X;
            to.apos.trDelta.Y = msg.ReadBoolean() ? msg.ReadFloat() : from.apos.trDelta.Y;
            to.apos.trDelta.Z = msg.ReadBoolean() ? msg.ReadFloat() : from.apos.trDelta.Z;
            to.apos.trDuration = msg.ReadBoolean() ? msg.ReadInt32() : from.apos.trDuration;
            to.apos.trTime = msg.ReadBoolean() ? msg.ReadInt32() : from.apos.trTime;
            to.apos.trType = msg.ReadBoolean() ? (Common.trType_t)msg.ReadInt32() : from.apos.trType;

            to.time = msg.ReadBoolean() ? msg.ReadInt32() : from.time;
            to.time2 = msg.ReadBoolean() ? msg.ReadInt32() : from.time2;

            to.origin.X = msg.ReadBoolean() ? msg.ReadFloat() : from.origin.X;
            to.origin.Y = msg.ReadBoolean() ? msg.ReadFloat() : from.origin.Y;
            to.origin.Z = msg.ReadBoolean() ? msg.ReadFloat() : from.origin.Z;
            to.origin2.X = msg.ReadBoolean() ? msg.ReadFloat() : from.origin2.X;
            to.origin2.Y = msg.ReadBoolean() ? msg.ReadFloat() : from.origin2.Y;
            to.origin2.Z = msg.ReadBoolean() ? msg.ReadFloat() : from.origin2.Z;

            to.angles.X = msg.ReadBoolean() ? msg.ReadFloat() : from.angles.X;
            to.angles.Y = msg.ReadBoolean() ? msg.ReadFloat() : from.angles.Y;
            to.angles.Z = msg.ReadBoolean() ? msg.ReadFloat() : from.angles.Z;
            to.angles2.X = msg.ReadBoolean() ? msg.ReadFloat() : from.angles2.X;
            to.angles2.Y = msg.ReadBoolean() ? msg.ReadFloat() : from.angles2.Y;
            to.angles2.Z = msg.ReadBoolean() ? msg.ReadFloat() : from.angles2.Z;

            to.otherEntityNum = msg.ReadBoolean() ? msg.ReadInt32() : from.otherEntityNum;
            to.otherEntityNum2 = msg.ReadBoolean() ? msg.ReadInt32() : from.otherEntityNum2;
            to.groundEntityNum = msg.ReadBoolean() ? msg.ReadInt32() : from.groundEntityNum;

            to.modelindex = msg.ReadBoolean() ? msg.ReadInt32() : from.modelindex;
            to.clientNum = msg.ReadBoolean() ? msg.ReadInt32() : from.clientNum;
            to.frame = msg.ReadBoolean() ? msg.ReadInt32() : from.frame;
            to.solid = msg.ReadBoolean() ? msg.ReadInt32() : from.solid;
            to.generic1 = msg.ReadBoolean() ? msg.ReadInt32() : from.generic1;
            int lenghtBits = msg.ReadInt32();

            dataStart = msg.Position - dataStart;
            lenghtBits -= dataStart;
            for (int i = 0; i < lenghtBits; i++)
            {
                msg.ReadBoolean();
            }
            middle = msg.Position - middle;

            //Common.Instance.WriteLine("MSG_ReadDeltaEntity: Read {0} bits", msg.Position - startBit);
        }
示例#25
0
        void ExecuteClientMessage(client_t cl, NetBuffer buf)
        {
            int serverId = buf.ReadInt32();
            cl.messageAcknowledge = buf.ReadInt32();
            if (cl.messageAcknowledge < 0)
            {
                // usually only hackers create messages like this
                // it is more annoying for them to let them hanging
                DropClient(cl, "Illegible client message");
                return;
            }

            cl.reliableAcknowledge = buf.ReadInt32();
            // NOTE: when the client message is fux0red the acknowledgement numbers
            // can be out of range, this could cause the server to send thousands of server
            // commands which the server thinks are not yet acknowledged in SV_UpdateServerCommandsToClient
            if (cl.reliableAcknowledge < cl.reliableSequence - 64)
            {
                DropClient(cl, "Illegible client message");
                cl.reliableAcknowledge = cl.reliableSequence;
                return;
            }

            // if this is a usercmd from a previous gamestate,
            // ignore it or retransmit the current gamestate
            //
            if (serverId != sv.serverId && !cl.lastClientCommandString.Equals("nextdl"))
            {
                if (serverId >= sv.restartedServerId && serverId < sv.serverId)
                {
                    // they just haven't caught the map_restart yet
                    Common.Instance.WriteLine("{0} : ignoring pre map_restart / outdated client message", cl.name);
                    return;
                }

                // if we can tell that the client has dropped the last
                // gamestate we sent them, resend it
                if (cl.messageAcknowledge > cl.gamestateMessageNum)
                {
                    Common.Instance.WriteLine("{0} : dropped gamestate, resending", cl.name);
                    SendClientGameState(cl);
                }
                return;
            }

            // this client has acknowledged the new gamestate so it's
            // safe to start sending it the real time again
            if (cl.oldServerTime > 0 && serverId == sv.serverId)
            {
                Common.Instance.WriteLine("{0} acknowledged gamestate", cl.name);
                cl.oldServerTime = 0;
            }

            // read optional clientCommand strings
            int c;
            do
            {
                c = buf.ReadByte();

                if (c == (int)clc_ops_e.clc_EOF)
                    break;

                if (c != (int)clc_ops_e.clc_clientCommand)
                    break;

                if (!ClientCommand(cl, buf))
                    break;  // we couldn't execute it because of the flood protection

                if (cl.state == clientState_t.CS_ZOMBIE)
                    return; // disconnect command
            } while (true);

            // read the usercmd_t
            if (c == (int)clc_ops_e.clc_move)
            {
                UserMove(cl, buf, true);
            }
            else if (c == (int)clc_ops_e.clc_moveNoDelta)
            {
                UserMove(cl, buf, false);
            }
            else if (c != (int)clc_ops_e.clc_EOF)
            {
                Common.Instance.WriteLine("WARNING: bad command byte for client {0}", cl.name);
            }
        }