Write() public méthode

Writes an endpoint description
public Write ( IPEndPoint endPoint ) : void
endPoint System.Net.IPEndPoint
Résultat void
Exemple #1
0
 public void Write(NetBuffer om)
 {
     if (MetaData == null) MetaData = "Null";
     om.Write(MetaData);
     om.Write(Data.Length);
     om.Write(Data);
 }
Exemple #2
0
        internal void DoSendDiscoveryRequest(
            IPEndPoint endPoint,
            bool useBroadcast,
            NetDiscoveryRequest request,
            float interval,
            float timeout)
        {
            if (!m_netBase.m_isBound)
                m_netBase.Start();

            if (request == null)
            {
                m_netBase.LogVerbose("Creating discovery request " + m_nextRequestNumber);
                request = new NetDiscoveryRequest(endPoint, m_nextRequestNumber++, useBroadcast, interval, timeout);
                if (m_requests == null)
                    m_requests = new List<NetDiscoveryRequest>();
                m_requests.Add(request);
            }

            string appIdent = m_netBase.m_config.ApplicationIdentifier;
            NetBuffer data = new NetBuffer(appIdent.Length + 8);

            // write app identifier
            data.Write(appIdent);

            // write netbase identifier to avoid self-discovery
            data.Write(m_netBase.m_randomIdentifier);

            // write request number
            data.Write((ushort)request.Number);

            m_netBase.LogWrite("Discovering " + endPoint.ToString() + "...");
            m_netBase.QueueSingleUnreliableSystemMessage(NetSystemType.Discovery, data, endPoint, useBroadcast);
        }
Exemple #3
0
 public override void Write(NetBuffer om)
 {
     base.Write(om);
     om.Write(FollowerId.Count);
     foreach(var obj in FollowerId)
     {
         om.Write(obj);
     }
 }
Exemple #4
0
        public void Write(NetBuffer om)
        {
            if (Address == null) Address = string.Empty;
            if (ConnectName == null) ConnectName = string.Empty;
            if (Information == null) ConnectName = string.Empty;

            om.Write(Address);
            om.Write(ConnectName);
            om.Write(Information);
        }
Exemple #5
0
 public override void Write(NetBuffer om)
 {
     base.Write(om);
     om.Write(Followers.Count);
     foreach(var obj in Followers)
     {
         om.Write(obj.Key);
         om.Write(obj.Value);
     }
 }
Exemple #6
0
 public void Write(NetBuffer om)
 {
     om.Write(MessagePacketId);
     om.Write(Number);
     if (Bytes != null)
     {
         om.Write(Bytes.Length);
         om.Write(Bytes);
     }
     else
     {
         om.Write(0);
     }
 }
Exemple #7
0
 public void Write(NetBuffer om)
 {
     if(Plugins != null)
     {
         om.Write(Plugins.Count);
         foreach (var obj in Plugins)
         {
             om.Write(obj);
         }
     }
     else
     {
         om.Write(0);
     }
 }
		internal void Encode(NetBuffer intoBuffer)
		{
			Debug.Assert(m_sequenceNumber != -1);

			// message type, netchannel and sequence number
			intoBuffer.Write((byte)((int)m_type | ((int)m_sequenceChannel << 3)));
			intoBuffer.Write((ushort)m_sequenceNumber);

			// payload length
			int len = m_data.LengthBytes;
			intoBuffer.WriteVariableUInt32((uint)len);

			// copy payload
			intoBuffer.Write(m_data.Data, 0, len);

			return;
		}
		internal void WriteStringTable(NetBuffer buffer, string str)
		{
			// Bits:
			// 0: Does the actual string follows? (if so, send confirmation)
			// 1: Is the value contained in the following 6 bits ONLY? (false = use one more byte for 14 bits total)
			// 2-7: value
			// 8-15: (possibly) value

			int val;
			if (!m_stringTable.TryGetValue(str, out val))
			{
				// new value
				val = m_stringTable.Count;
				if (val >= c_maxTabledStrings)
				{
					val = 0;
				}
				else
				{
					m_stringTableLookUp[val] = str;

					val |= (1 << 16); // 1 means not acknowledged yet
					m_stringTable[str] = val;
				}
			}

			// is it known at destination?
			bool known = (val < (1 << 16));
			ushort actualVal = (ushort)val;

			buffer.Write(known);
			if (actualVal < 64)
			{
				buffer.Write(false);
				buffer.Write(actualVal, 6);
			} else {
				buffer.Write(true);
				buffer.Write(actualVal, 6 + 8);
			}
			if (!known)
				buffer.Write(str);
		}
        public void HandlesAllItemsOnTheMessage()
        {
            var msg = new Message() { Items = { new Item() { Type = ItemType.SuccessfulJoin, Data = 143 }, new Item() { Type = ItemType.NewClient, Data = 3 }, new Item() { Type = ItemType.Player, Data = new Frenetic.Player.PlayerState() } } };
            NetBuffer buffer = new NetBuffer();
            buffer.Write(msg);
            stubNetClient.Stub(me => me.CreateBuffer()).Return(buffer);
            stubNetClient.Stub(me => me.ReadMessage(Arg<NetBuffer>.Is.Equal(buffer), out Arg<NetMessageType>.Out(NetMessageType.Data).Dummy)).Return(true);
            clientNetworkSession.ClientJoined += delegate { };

            var unprocessedMsg = clientNetworkSession.ReadNextMessage();

            Assert.AreEqual(1, unprocessedMsg.Items.Count);
            Assert.AreEqual(ItemType.Player, unprocessedMsg.Items[0].Type);
        }
Exemple #11
0
 public NetBuffer ToBuffer()
 {
     if(IsComplete)
     {
         var Buffer  = new NetBuffer();
         var t       = from p in PacketList orderby p.Number select p;
         foreach(var obj in t)
         {
             Buffer.Write(obj.Bytes);
         }
         return Buffer;
     }
     return null;
 }
        public void ServerReceivesDataFromClientAndCreatesMessage()
        {
            NetBuffer tmpBuffer = new NetBuffer();
            tmpBuffer.Write(new Message() { Items = { new Item() { Type = ItemType.NewClient, Data = 10 } } });
            stubNetServer.Stub(x => x.CreateBuffer()).Return(tmpBuffer);
            stubNetServer.Stub(x => x.ReadMessage(Arg<NetBuffer>.Is.Anything,
                            out Arg<NetMessageType>.Out(NetMessageType.Data).Dummy,
                            out Arg<INetConnection>.Out(stubNetConnection).Dummy))
                            .Return(true);

            Message msg = serverNetworkSession.ReadNextMessage();

            stubNetServer.AssertWasCalled(x => x.ReadMessage(Arg<NetBuffer>.Is.Equal(tmpBuffer),
                                        out Arg<NetMessageType>.Out(NetMessageType.Data).Dummy,
                                        out Arg<INetConnection>.Out(stubNetConnection).Dummy));
            Assert.AreEqual(ItemType.NewClient, msg.Items[0].Type);
            Assert.AreEqual(10, msg.Items[0].Data);
        }
        internal string ReadStringTable(NetBuffer buffer)
        {
            byte b = buffer.ReadByte();

            bool stringFollows = ((b & 1) == 0);
            bool shortVal = ((b & 2) == 0);

            int val = 0;
            if (shortVal)
                val = b >> 2;
            else
                val = ((b & (255 << 2)) << 6) | buffer.ReadByte();

            string retval = string.Empty;
            if (stringFollows)
            {
                retval = buffer.ReadString();

                m_stringTable[retval] = val;
                m_stringTableLookUp[val] = retval;

                //
                // Send confirmation
                //
                NetBuffer buf = new NetBuffer(2);
                buf.Write((ushort)val);
                m_owner.QueueSingleUnreliableSystemMessage(
                    NetSystemType.StringTableAck,
                    buf,
                    m_remoteEndPoint,
                    false
                );

                return retval;
            }

            if (!m_stringTableLookUp.TryGetValue(val, out retval))
            {
                // Ack! Failed to find string table value!
                throw new Exception("ACK!");
            }
            return retval;
        }
Exemple #14
0
 public void Write(NetBuffer om)
 {
     om.Write(PluginName);
     om.Write(MethodName);
     om.Write(RspType);
     if (RspType == StringDataType)
     {
         om.Write(StringCommandRsp);
     }
     else if (RspType == BinaryDataType)
     {
         om.Write(BinaryCommandRsp.Length);
         om.Write(BinaryCommandRsp);
     }
 }
Exemple #15
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");
		}
        public static void Main(string[] args)
        {
            setupNetwork();

            // create a buffer to read data into
            NetBuffer buffer = client.CreateBuffer();

            s_keepGoing = true;
            while (s_keepGoing)
            {
                NetMessageType type;

                // check if any messages has been received
                while (client.ReadMessage(buffer, out type))
                {

                    switch (type)
                    {
                        case NetMessageType.ServerDiscovered:
                            // just connect to any server found!

                            // make hail
                            NetBuffer buf = client.CreateBuffer();
                            buf.Write("Hail from " + Environment.MachineName);
                            client.Connect(buffer.ReadIPEndPoint(), buf.ToArray());
                            break;
                        case NetMessageType.ConnectionRejected:
                            Console.WriteLine("Rejected: " + buffer.ReadString());
                            break;
                        case NetMessageType.DebugMessage:
                        case NetMessageType.VerboseDebugMessage:
                            Console.WriteLine(buffer.ReadString());
                            break;
                        case NetMessageType.StatusChanged:
                            string statusMessage = buffer.ReadString();
                            Console.WriteLine("New status:   (" + statusMessage + ")");
                            break;
                        case NetMessageType.Data:
                            // The server sent this data!
                            string msg = buffer.ReadString();
                            Console.WriteLine(msg);
                            break;
                    }
                }

                update();

                if (client.Status == NetConnectionStatus.Connected)
                {
                    NetBuffer sendBuffer = new NetBuffer();
                    sendBuffer.Write(" ApacheNetworkObject:VBS2:foo:" + _x + ":" + _y + ":" + _z + ":" + _pitch + ":" + _yaw + ":" + _roll);
                    client.SendMessage(sendBuffer, NetChannel.ReliableInOrder14);
                }
                else
                {
                    Console.Out.WriteLine("Client lost connection....");
                    s_keepGoing = false;
                }

                Thread.Sleep(10);
            }

            client.Shutdown("Application exiting");
        }
Exemple #17
0
        /*
        =============
        SV_EmitPacketEntities

        Writes a delta update of an entityState_t list to the message.
        =============
        */
        void EmitPacketEntities(clientSnapshot_t from, clientSnapshot_t to, NetBuffer msg)
        {
            int fromnumentities = 0;

            if (from != null)
                fromnumentities = from.num_entities;

            Common.entityState_t oldent = null, newent = null;
            int oldindex = 0, newindex = 0;
            int newnum, oldnum;
            while (newindex < to.num_entities || oldindex < fromnumentities)
            {
                if (newindex >= to.num_entities)
                    newnum = 9999;
                else
                {
                    newent = snapshotEntities[(to.first_entity + newindex) % numSnapshotEntities];
                    newnum = newent.number;
                }

                if (oldindex >= fromnumentities)
                    oldnum = 9999;
                else
                {
                    oldent = snapshotEntities[(from.first_entity + oldindex) % numSnapshotEntities];
                    oldnum = oldent.number;
                }

                if (newnum == oldnum)
                {
                    // delta update from old position
                    // because the force parm is qfalse, this will not result
                    // in any bytes being emited if the entity has not changed at all
                    Net.Instance.MSG_WriteDeltaEntity(msg, ref oldent, ref newent, false);
                    oldindex++;
                    newindex++;
                    continue;
                }

                if (newnum < oldnum)
                {
                    // this is a new entity, send it from the baseline
                    Net.Instance.MSG_WriteDeltaEntity(msg, ref sv.svEntities[newnum].baseline, ref newent, true);
                    newindex++;
                    continue;
                }

                if (newnum > oldnum)
                {
                    // the old entity isn't present in the new message
                    Common.entityState_t nullEnt = null;
                    Net.Instance.MSG_WriteDeltaEntity(msg, ref oldent, ref nullEnt, true);
                    oldindex++;
                    continue;
                }
            }

            msg.Write(1023);    // end of packetentities
        }
 private void WriteRoundStartMessage(NetBuffer buffer, Player player)
 {
     if (player == null)
     {
         buffer.Write(false); // player is not ready
         buffer.Write(true);  // player needs field state
     }
     else
     {
         buffer.Write(player.IsReady);
         buffer.Write(player.needsFieldState);
     }
 }
 private void WriteRoundEndMessage(NetBuffer buffer, Player player)
 {
     buffer.Write(player.IsReady);
     buffer.Write(player.needsRoundResults);
 }
Exemple #20
0
        void WriteSnapshotToClient(client_t cl, NetBuffer msg)
        {
            // this is the snapshot we are creating
            clientSnapshot_t frame = cl.frames[cl.netchan.outgoingSequence & 31];

            // try to use a previous frame as the source for delta compressing the snapshot
            clientSnapshot_t oldframe = null;
            int lastframe;
            if (cl.deltaMessage <= 0 || cl.state != clientState_t.CS_ACTIVE)
            {
                // client is asking for a retransmit
                oldframe = null;
                lastframe = 0;
            }
            else if (cl.netchan.outgoingSequence - cl.deltaMessage >= (32 - 3))
            {
                // client hasn't gotten a good message through in a long time
                Common.Instance.WriteLine("{0}:  Delta request from out of date packet.", cl.name);
                oldframe = null;
                lastframe = 0;
            }
            else
            {
                // we have a valid snapshot to delta from
                oldframe = cl.frames[cl.deltaMessage & 31];
                lastframe = cl.netchan.outgoingSequence - cl.deltaMessage;
                // the snapshot's entities may still have rolled off the buffer, though
                if (oldframe.first_entity <= nextSnapshotEntities - numSnapshotEntities)
                {
                    Common.Instance.WriteLine("{0}: Delta request from out of date entities.", cl.name);
                    oldframe = null;
                    lastframe = 0;
                }
            }

            msg.Write((byte)svc_ops_e.svc_snapshot);
            // send over the current server time so the client can drift
            // its view of time to try to match
            if (cl.oldServerTime > 0)
            {
                // The server has not yet got an acknowledgement of the
                // new gamestate from this client, so continue to send it
                // a time as if the server has not restarted. Note from
                // the client's perspective this time is strictly speaking
                // incorrect, but since it'll be busy loading a map at
                // the time it doesn't really matter.
                msg.Write((int)(sv.time + cl.oldServerTime));
            }
            else
                msg.Write((int)sv.time);

            // what we are delta'ing from
            msg.Write((byte)lastframe);

            int snapFlags = snapFlagServerBit;
            if (cl.rateDelayed)
                snapFlags |= SNAPFLAG_RATE_DELAYED;
            if (cl.state != clientState_t.CS_ACTIVE)
                snapFlags |= SNAPFLAG_NOT_ACTIVE;

            msg.Write((byte)snapFlags);

            // send over the areabits
            msg.Write((byte)frame.areabytes);
            msg.Write(frame.areabits);

            // delta encode the playerstate
            if (oldframe != null)
                Net.WriteDeltaPlayerstate(msg, oldframe.ps, frame.ps);
            else
                Net.WriteDeltaPlayerstate(msg, null, frame.ps);

            // delta encode the entities
            EmitPacketEntities(oldframe, frame, msg);
        }
Exemple #21
0
		static void Main(string[] args)
		{
			// create a client with a default configuration
			NetConfiguration config = new NetConfiguration("chatApp");
			NetClient client = new NetClient(config);
			client.SetMessageTypeEnabled(NetMessageType.ConnectionRejected, true);
			client.SetMessageTypeEnabled(NetMessageType.DebugMessage, true);
			//client.SetMessageTypeEnabled(NetMessageType.VerboseDebugMessage, true);
			client.Start();

			// Wait half a second to allow server to start up if run via Visual Studio
			Thread.Sleep(500);

			// Emit discovery signal
			client.DiscoverLocalServers(14242);

			// create a buffer to read data into
			NetBuffer buffer = client.CreateBuffer();

			// current input string
			string input = "";

			// keep running until the user presses a key
			Console.WriteLine("Type 'quit' to exit client");
			Console.CancelKeyPress += new ConsoleCancelEventHandler(Console_CancelKeyPress);
			s_keepGoing = true;
			while (s_keepGoing)
			{
				NetMessageType type;

				// check if any messages has been received
				while (client.ReadMessage(buffer, out type))
				{
					switch (type)
					{
						case NetMessageType.ServerDiscovered:
							// just connect to any server found!

							// make hail
							NetBuffer buf = client.CreateBuffer();
							buf.Write("Hail from " + Environment.MachineName);
							client.Connect(buffer.ReadIPEndPoint(), buf.ToArray());
							break;
						case NetMessageType.ConnectionRejected:
							Console.WriteLine("Rejected: " + buffer.ReadString());
							break;
						case NetMessageType.DebugMessage:
						case NetMessageType.VerboseDebugMessage:
							Console.WriteLine(buffer.ReadString());
							break;
						case NetMessageType.StatusChanged:
							string statusMessage = buffer.ReadString();
							NetConnectionStatus newStatus = (NetConnectionStatus)buffer.ReadByte();
							Console.WriteLine("New status: " + newStatus + " (" + statusMessage + ")");
							break;
						case NetMessageType.Data:
							// The server sent this data!
							string msg = buffer.ReadString();
							Console.WriteLine(msg);
							break;
					}
				}

				while (Console.KeyAvailable)
				{
					ConsoleKeyInfo ki = Console.ReadKey();
					if (ki.Key == ConsoleKey.Enter)
					{
						if (!string.IsNullOrEmpty(input))
						{
							if (input == "quit")
							{
								// exit application
								s_keepGoing = false;
							}
							else
							{
								// Send chat message
								NetBuffer sendBuffer = new NetBuffer();
								sendBuffer.Write(input);
								client.SendMessage(sendBuffer, NetChannel.ReliableInOrder1);
								input = "";
							}
						}
					}
					else
					{
						input += ki.KeyChar;
					}
				}

				Thread.Sleep(1);
			}

			client.Shutdown("Application exiting");
		}
Exemple #22
0
 public virtual void Write(NetBuffer om)
 {
     om.Position = 0;
     om.Write(Id);
     om.WriteAllProperties(this);
 }
Exemple #23
0
        /*
        ==================
        SV_UpdateServerCommandsToClient

        (re)send all server commands the client hasn't acknowledged yet
        ==================
        */
        void UpdateServerCommandsToClient(client_t cl, NetBuffer msg)
        {
            // write any unacknowledged serverCommands
            for (int i = cl.reliableAcknowledge+1; i <= cl.reliableSequence; i++)
            {
                msg.Write((byte)svc_ops_e.svc_serverCommand);
                msg.Write(i);
                msg.Write(cl.reliableCommands[i & 63]);
            }
            cl.reliableSent = cl.reliableSequence;
        }
            public void WriteToBuffer(NetBuffer buffer)
            {
                buffer.Write((byte)CommandType.ParticleUpdate);
                 buffer.Write(this.game.Time.NumericValue);
                 buffer.Write((byte)this.parameters.Count);

                 foreach (var p in this.parameters)
                 {
                     buffer.Write(p);
                 }
            }
Exemple #25
0
 public void Write(NetBuffer om)
 {
     om.Write(Command);
 }
Exemple #26
0
        // TODO: Use this with TRUE isLibraryThread for internal sendings (acks etc)

        internal void SendMessage(NetBuffer data, NetChannel channel, NetBuffer receiptData, bool isLibraryThread)
        {
            if (m_status != NetConnectionStatus.Connected)
            {
                throw new NetException("Status must be Connected to send messages");
            }

            if (data.LengthBytes > m_owner.m_config.m_maximumTransmissionUnit)
            {
                //
                // Fragmented message
                //

                int dataLen      = data.LengthBytes;
                int chunkSize    = m_owner.m_config.m_maximumTransmissionUnit - 10;              // header
                int numFragments = dataLen / chunkSize;
                if (chunkSize * numFragments < dataLen)
                {
                    numFragments++;
                }

                ushort fragId = m_nextSendFragmentId++;

                for (int i = 0; i < numFragments; i++)
                {
                    OutgoingNetMessage fmsg = m_owner.CreateOutgoingMessage();
                    fmsg.m_type    = NetMessageLibraryType.UserFragmented;
                    fmsg.m_msgType = NetMessageType.Data;

                    NetBuffer fragBuf = m_owner.CreateBuffer();
                    fragBuf.Write(fragId);
                    fragBuf.WriteVariableUInt32((uint)i);
                    fragBuf.WriteVariableUInt32((uint)numFragments);

                    if (i < numFragments - 1)
                    {
                        // normal fragment
                        fragBuf.Write(data.Data, i * chunkSize, chunkSize);
                    }
                    else
                    {
                        // last fragment
                        int bitsInLast  = data.LengthBits - (chunkSize * (numFragments - 1) * 8);
                        int bytesInLast = dataLen - (chunkSize * (numFragments - 1));
                        fragBuf.Write(data.Data, i * chunkSize, bytesInLast);

                        // add receipt only to last message
                        fmsg.m_receiptData = receiptData;
                    }
                    fmsg.m_data            = fragBuf;
                    fmsg.m_data.m_refCount = 1;                     // since it's just been created

                    fmsg.m_numSent         = 0;
                    fmsg.m_nextResend      = double.MaxValue;
                    fmsg.m_sequenceChannel = channel;
                    fmsg.m_sequenceNumber  = -1;

                    if (isLibraryThread)
                    {
                        m_unsentMessages.Enqueue(fmsg);
                    }
                    else
                    {
                        lock (m_lockedUnsentMessages)
                            m_lockedUnsentMessages.Enqueue(fmsg);
                    }
                }

                // TODO: recycle the original, unfragmented data

                return;
            }

            //
            // Normal, unfragmented, message
            //

            OutgoingNetMessage msg = m_owner.CreateOutgoingMessage();

            msg.m_msgType = NetMessageType.Data;
            msg.m_type    = NetMessageLibraryType.User;
            msg.m_data    = data;
            msg.m_data.m_refCount++;             // it could have been sent earlier also
            msg.m_numSent         = 0;
            msg.m_nextResend      = double.MaxValue;
            msg.m_sequenceChannel = channel;
            msg.m_sequenceNumber  = -1;
            msg.m_receiptData     = receiptData;

            if (isLibraryThread)
            {
                m_unsentMessages.Enqueue(msg);
            }
            else
            {
                lock (m_lockedUnsentMessages)
                    m_lockedUnsentMessages.Enqueue(msg);
            }
        }
 public void Write(NetBuffer om)
 {
     om.Write(ConnectionType);
 }
Exemple #28
0
        /*
        ==================
        MSG_WriteDeltaEntity

        Writes part of a packetentities message, including the entity number.
        Can delta from either a baseline or a previous packet_entity
        If to is NULL, a remove entity update will be sent
        If force is not set, then nothing at all will be generated if the entity is
        identical, under the assumption that the in-order delta code will catch it.
        ==================
        */
        public void MSG_WriteDeltaEntity(NetBuffer msg, ref Common.entityState_t from, ref Common.entityState_t to, bool force)
        {
            int msgStart = msg.LengthBits;
            // a NULL to is a delta remove message
            if (to == null)
            {
                if (from == null)
                    return;
                msg.Write(from.number);
                msg.Write(true);
                return;
            }

            if (to.number < 0 || to.number >= 1024)
            {
                Common.Instance.Error("MSG_WriteDeltaEntity: Bad entity number: " + to.number);
            }

            NetBuffer buf = new NetBuffer();
            //NetBuffer buf = msg;
            int lc = 0;
            //if (from.number != to.number) { lc = 1; buf.Write(true); buf.Write(to.number); } else { buf.Write(false); }
            if (from.eType != to.eType) { lc = 2; buf.Write(true); buf.Write(to.eType); } else { buf.Write(false); }
            if (from.eFlags != to.eFlags) { lc = 3; buf.Write(true); buf.Write((int)to.eFlags); } else { buf.Write(false); }
            int middle = buf.LengthBits;
            if (from.pos.trBase.X != to.pos.trBase.X) { lc = 4; buf.Write(true); buf.Write(to.pos.trBase.X); } else { buf.Write(false); }
            if (from.pos.trBase.Y != to.pos.trBase.Y) { lc = 5; buf.Write(true); buf.Write(to.pos.trBase.Y); } else { buf.Write(false); }
            if (from.pos.trBase.Z != to.pos.trBase.Z) { lc = 6; buf.Write(true); buf.Write(to.pos.trBase.Z); } else { buf.Write(false); }
            if (from.pos.trDelta.X != to.pos.trDelta.X) {
                lc = 7; buf.Write(true); buf.Write(to.pos.trDelta.X); } else { buf.Write(false); }
            if (from.pos.trDelta.Y != to.pos.trDelta.Y) { lc = 8; buf.Write(true); buf.Write(to.pos.trDelta.Y); } else { buf.Write(false); }
            if (from.pos.trDelta.Z != to.pos.trDelta.Z) { lc = 9; buf.Write(true); buf.Write(to.pos.trDelta.Z); } else { buf.Write(false); }
            if (from.pos.trDuration != to.pos.trDuration) { lc = 10; buf.Write(true); buf.Write(to.pos.trDuration); } else { buf.Write(false); }
            if (from.pos.trTime != to.pos.trTime) { lc = 11; buf.Write(true); buf.Write(to.pos.trTime); } else { buf.Write(false); }
            if (from.pos.trType != to.pos.trType) { lc = 12; buf.Write(true); buf.Write((int)to.pos.trType); } else { buf.Write(false); }

            if (from.apos.trBase.X != to.apos.trBase.X) { lc = 13; buf.Write(true); buf.Write(to.apos.trBase.X); } else { buf.Write(false); }
            if (from.apos.trBase.Y != to.apos.trBase.Y) { lc = 14; buf.Write(true); buf.Write(to.apos.trBase.Y); } else { buf.Write(false); }
            if (from.apos.trBase.Z != to.apos.trBase.Z) { lc = 15; buf.Write(true); buf.Write(to.apos.trBase.Z); } else { buf.Write(false); }
            if (from.apos.trDelta.X != to.apos.trDelta.X) { lc = 16; buf.Write(true); buf.Write(to.apos.trDelta.X); } else { buf.Write(false); }
            if (from.apos.trDelta.Y != to.apos.trDelta.Y) { lc = 17; buf.Write(true); buf.Write(to.apos.trDelta.Y); } else { buf.Write(false); }
            if (from.apos.trDelta.Z != to.apos.trDelta.Z) { lc = 18; buf.Write(true); buf.Write(to.apos.trDelta.Z); } else { buf.Write(false); }
            if (from.apos.trDuration != to.apos.trDuration) { lc = 19; buf.Write(true); buf.Write(to.apos.trDuration); } else { buf.Write(false); }
            if (from.apos.trTime != to.apos.trTime) { lc = 20; buf.Write(true); buf.Write(to.apos.trTime); } else { buf.Write(false); }
            if (from.apos.trType != to.apos.trType) { lc = 21; buf.Write(true); buf.Write((int)to.apos.trType); } else { buf.Write(false); }

            if (from.time != to.time) { lc = 22; buf.Write(true); buf.Write(to.time); } else { buf.Write(false); }
            if (from.time2 != to.time2) { lc = 23; buf.Write(true); buf.Write(to.time2); } else { buf.Write(false); }

            if (from.origin.X != to.origin.X) { lc = 24; buf.Write(true); buf.Write(to.origin.X); } else { buf.Write(false); }
            if (from.origin.Y != to.origin.Y) { lc = 25; buf.Write(true); buf.Write(to.origin.Y); } else { buf.Write(false); }
            if (from.origin.Z != to.origin.Z) { lc = 26; buf.Write(true); buf.Write(to.origin.Z); } else { buf.Write(false); }
            if (from.origin2.X != to.origin2.X) { lc = 27; buf.Write(true); buf.Write(to.origin2.X); } else { buf.Write(false); }
            if (from.origin2.Y != to.origin2.Y) { lc = 28; buf.Write(true); buf.Write(to.origin2.Y); } else { buf.Write(false); }
            if (from.origin2.Z != to.origin2.Z) { lc = 29; buf.Write(true); buf.Write(to.origin2.Z); } else { buf.Write(false); }

            if (from.angles.X != to.angles.X) { lc = 30; buf.Write(true); buf.Write(to.angles.X); } else { buf.Write(false); }
            if (from.angles.Y != to.angles.Y) { lc = 31; buf.Write(true); buf.Write(to.angles.Y); } else { buf.Write(false); }
            if (from.angles.Z != to.angles.Z) { lc = 32; buf.Write(true); buf.Write(to.angles.Z); } else { buf.Write(false); }
            if (from.angles2.X != to.angles2.X) { lc = 33; buf.Write(true); buf.Write(to.angles2.X); } else { buf.Write(false); }
            if (from.angles2.Y != to.angles2.Y) { lc = 34; buf.Write(true); buf.Write(to.angles2.Y); } else { buf.Write(false); }
            if (from.angles2.Z != to.angles2.Z) { lc = 35; buf.Write(true); buf.Write(to.angles2.Z); } else { buf.Write(false); }

            if (from.otherEntityNum != to.otherEntityNum) { lc = 36; buf.Write(true); buf.Write(to.otherEntityNum); } else { buf.Write(false); }
            if (from.otherEntityNum2 != to.otherEntityNum2) { lc = 37; buf.Write(true); buf.Write(to.otherEntityNum2); } else { buf.Write(false); }

            if (from.groundEntityNum != to.groundEntityNum) { lc = 38; buf.Write(true); buf.Write(to.groundEntityNum); } else { buf.Write(false); }

            if (from.modelindex != to.modelindex) { lc = 39; buf.Write(true); buf.Write(to.modelindex); } else { buf.Write(false); }
            if (from.clientNum != to.clientNum) { lc = 40; buf.Write(true); buf.Write(to.clientNum); } else { buf.Write(false); }
            if (from.frame != to.frame) { lc = 41; buf.Write(true); buf.Write(to.frame); } else { buf.Write(false); }

            if (from.solid != to.solid) { lc = 42; buf.Write(true); buf.Write(to.solid); } else { buf.Write(false); }
            if (from.generic1 != to.generic1) { lc = 43; buf.Write(true); buf.Write(to.generic1); } else { buf.Write(false); }

            if (lc == 0)
            {
                // nothing at all changed
                if (!force)
                {
                    return;		// nothing at all
                }
                // write two bits for no change
                msg.Write(to.number);
                msg.Write(false);   // not removed
                msg.Write(false);   // no delta
                return;
            }

            msg.Write(to.number);
            msg.Write(false);   // not removed
            msg.Write(true);    // we have a delta

            //msg.Write(lc);  // # of changes
            //msg.CopyFrom(buf);
            int msgPos = msg.LengthBits;
            //msg.Write(buf.Data);
            WriteDeltaEntityHags(msg, ref  from,ref  to);
            msg.Write(buf.LengthBits);

            //Common.Instance.WriteLine("MSG_WriteDeltaEntity: Wrote {0} bits", msg.LengthBits - msgStart);
        }
Exemple #29
0
        //public static void WriteMessageToRemotePlayer(NetPeer peer, GameOptions gameOpts)
        //{
        //    byte[] serializedGameOptions;
        //    MemoryStream ms = new MemoryStream();
        //    BinaryFormatter bf1 = new BinaryFormatter();
        //    bf1.Serialize(ms, gameOpts);
        //    serializedGameOptions =  ms.ToArray();

        //    NetBuffer buffer = new NetBuffer(serializedGameOptions);

        //    peer.SendToAll(buffer, NetChannel.ReliableInOrder1);
        //}


        public static void WriteMessageToRemotePlayer(NetPeer peer, String msg)
        {
            Lidgren.Network.NetBuffer buff = new Lidgren.Network.NetBuffer();
            buff.Write(msg);
            peer.SendToAll(buff, Lidgren.Network.NetChannel.ReliableInOrder1);
        }
Exemple #30
0
		private static void SendPacket()
		{
			NetBuffer buf = m_client.CreateBuffer();
			buf.EnsureBufferSize(m_nextSize * 8);

			int cnt = m_nextSize / 4;
			for (int i = 0; i < cnt; i++)
				buf.Write(i);

			NativeMethods.AppendText(m_mainForm.richTextBox1, "Sending " + m_nextSize + " byte packet");

			// any receipt data will do
			NetBuffer receipt = new NetBuffer(4);
			receipt.Write(m_nextSize);
			m_client.SendMessage(buf, NetChannel.ReliableInOrder4, receipt);
		}
Exemple #31
0
        void SendClientSnapshot(client_t client, int index)
        {
            // build the snapshot
            BuildClientSnapshot(client, index);

            NetBuffer msg = new NetBuffer();
            // let the client know which reliable clientCommands we have received
            msg.Write(client.lastClientCommand);
            // (re)send any reliable server commands
            UpdateServerCommandsToClient(client, msg);

            // send over all the relevant entityState_t
            // and the playerState_t
            WriteSnapshotToClient(client, msg);

            SendMessageToClient(msg, client);
        }
Exemple #32
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;
        }