ReadString() public method

Reads a string written using Write(string) and returns true for success
public ReadString ( string &result ) : bool
result string
return bool
Exemplo n.º 1
0
        private void receive()
        {
            NetBuffer buffer = new NetBuffer();

            bool keepGoing = true;
            while (keepGoing)
            {
                NetIncomingMessage message;
                while ((message = client.ReadMessage()) != null)
                {
                    switch (message.MessageType)
                    {
                        case NetIncomingMessageType.DebugMessage:
                            Console.WriteLine(buffer.ReadString());
                            break;

                        case NetIncomingMessageType.StatusChanged:
                            Console.WriteLine("New status: " + client.Status + " (Reason: " + buffer.ReadString() + ")");
                            if(client.Status != NetPeerStatus.Running)
                            {
                                keepGoing = false;
                                break;
                            }
                            break;

                        case NetIncomingMessageType.Data:
                            // Handle data in buffer here
                            break;
                    }
                }
            }
        }
Exemplo n.º 2
0
        private static void HandleMessage(NetMessageType type, NetConnection source, NetBuffer buffer)
        {
            switch (type)
            {
                case NetMessageType.DebugMessage:
                    WriteToConsole(buffer.ReadString());
                    break;
                case NetMessageType.StatusChanged:
                    WriteToConsole("New status: " + source.Status + " (" + buffer.ReadString() + ")");
                    UpdateStatisticsDisplay(source);
                    break;
                case NetMessageType.Data:
                    //System.IO.File.AppendAllText("C:\\receivedpackets.txt", s_userMessagesReceived.ToString() + ": " + msg.ReadString() + " (" + msg.m_sequenceNumber + ")" + Environment.NewLine);
                    s_userMessagesReceived++;

                    // simulate some processing of the message here
                    for (int i = 0; i < buffer.LengthBytes - 2; i++)
                        buffer.ReadByte();

                    // check checksum
                    ushort checksum = NetChecksum.Adler16(buffer.Data, 0, buffer.LengthBytes - 2);
                    ushort given = buffer.ReadUInt16();
                    if (checksum != given)
                        WriteToConsole("Wrong checksum! Expected " + checksum + " found given " + given);

                    double b = s_userMessagesReceived;
                    for (int i = 0; i < 1000; i++)
                        b += Math.Sqrt((double)i) / Math.Sin(s_tmp);
                    s_tmp += b / 10000.0;
                    break;
                default:
                    break;
            }
        }
Exemplo n.º 3
0
		private static void HandleMessage(NetMessageType type, NetConnection source, NetBuffer buffer)
		{
			switch (type)
			{
				case NetMessageType.StatusChanged:
					if (source.LocalHailData == null)
						source.LocalHailData = Encoding.ASCII.GetBytes("Hi; I'm " + s_peer.GetHashCode());
					if (source.RemoteHailData != null)
						WriteToConsole("New status: " + source.Status + " - remote hail is: " + Encoding.ASCII.GetString(source.RemoteHailData));
					else
						WriteToConsole("New status: " + source.Status + " - remote hail is null");
					break;
				case NetMessageType.DebugMessage:
				case NetMessageType.VerboseDebugMessage:
				case NetMessageType.BadMessageReceived:
				case NetMessageType.ConnectionRejected:
					WriteToConsole(buffer.ReadString());
					break;
				case NetMessageType.Data:
					WriteToConsole(source.RemoteEndpoint + " writes: " + buffer.ReadString());
					break;
				case NetMessageType.ServerDiscovered:
					// discovered another peer!
					s_peer.Connect(buffer.ReadIPEndPoint(), Encoding.ASCII.GetBytes("Hi; I'm " + s_peer.GetHashCode()));
					break;
				default:
					// unhandled
					break;
			}
		}
Exemplo n.º 4
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);
     }
 }
Exemplo n.º 5
0
        public static void StatusChangeHandler(NetClient client, NetBuffer buffer)
        {
            string status_msg = buffer.ReadString();
            NetConnectionStatus status = (NetConnectionStatus)buffer.ReadByte();

            if (status == NetConnectionStatus.Connected)
            {
                Console.WriteLine("Client: Connected");

                Console.Write("Client: Starting IOS");

                int i;
                for (i = 0; i < 10; i++)
                {
                    Console.Write(".");
                    Thread.Sleep(500);
                }
                Console.WriteLine("");

                //Show the IOS Master form
                System.Windows.Forms.Application.EnableVisualStyles();
                System.Windows.Forms.Application.SetCompatibleTextRenderingDefault(false);
                System.Windows.Forms.Application.Run(new MasterForm());
            }

            if (status == NetConnectionStatus.Disconnected)
            {
                Console.WriteLine("Client: Disconnected - " + status_msg);
            }
        }
Exemplo n.º 6
0
 private static void HandleMessage(NetMessageType type, NetConnection source, NetBuffer buffer)
 {
     switch (type)
     {
         case NetMessageType.DebugMessage:
             Console.WriteLine(buffer.ReadString());
             break;
         case NetMessageType.StatusChanged:
             NetConnectionStatus status = source.Status;
             if (status == NetConnectionStatus.Connected)
             {
                 source.Tag = ImageClientStatus.JustConnected;
                 s_nextPixelToSend[source] = 0;
             }
             else if (status == NetConnectionStatus.Disconnected)
             {
                 if (s_nextPixelToSend.ContainsKey(source))
                     s_nextPixelToSend.Remove(source);
             }
             break;
         case NetMessageType.Receipt:
             source.Tag = ImageClientStatus.Running;
             break;
         default:
             // unhandled
             break;
     }
 }
Exemplo n.º 7
0
        public static void Process(NetServer server, NetBuffer buffer, NetConnection sender)
        {
            Config config = Config.Instance;

            List<NetConnection> connections = server.Connections;

            //Lets send that message onto any plugin clients
            foreach (NetConnection connection in connections)
            {
                if (config.Server.client_connections.ContainsKey(connection.RemoteEndpoint.ToString()))
                {
                    string client_type = (string)config.Server.client_connections[connection.RemoteEndpoint.ToString()];

                    if (client_type.ToLower() == "plugin")
                    {
                        string msg = buffer.ReadString();

                        Console.WriteLine("Slave: Data sent - " + msg);

                        NetBuffer slavebuf = server.CreateBuffer();

                        slavebuf.Write(msg);

                        server.SendMessage(slavebuf, connection, NetChannel.ReliableInOrder4);
                    }
                }
            }
        }
Exemplo n.º 8
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
        }
Exemplo n.º 9
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;
        }
Exemplo n.º 10
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);
            }
        }
Exemplo n.º 11
0
        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);
        }
Exemplo n.º 12
0
        public static void StatusChangeHandler(NetClient client, NetBuffer buffer)
        {
            string status_msg = buffer.ReadString();
            NetConnectionStatus status = (NetConnectionStatus)buffer.ReadByte();

            if (status == NetConnectionStatus.Connected)
            {
                Console.WriteLine("Plugin: Connected");
            }

            if (status == NetConnectionStatus.Disconnected)
            {
                Console.WriteLine("Plugin: Disconnected");
            }
        }
        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;
        }
Exemplo n.º 14
0
        public static void DataHandler(NetClient client, NetBuffer buffer)
        {
            //Check which page to load
            string[] requested_page = buffer.ReadString().Split(':');
            string page = requested_page[1];

            Console.WriteLine("Requested page: " + page);

            Config config = Config.Instance;

            //Close any running forms
            if (config.Client.form_thread != null)
            {
                config.Client.form_thread.Abort();

                if (config.Client.form_active == "metar")
                {
                    config.Client.metar_form.Close();
                }

                if (config.Client.form_active == "wind")
                {
                    config.Client.wind_form.Close();
                }
            }

            if (page == "metar")
            {
                config.Client.form_active = "metar";

                config.Client.form_thread = new Thread(new ThreadStart(RunForm));
                config.Client.form_thread.Start();
            }

            if (page == "wind")
            {
                config.Client.form_active = "wind";

                config.Client.form_thread = new Thread(new ThreadStart(RunForm));
                config.Client.form_thread.Start();
            }
        }
Exemplo n.º 15
0
		private static void HandleMessage(NetMessageType type, NetBuffer data)
		{
			switch (type)
			{
				case NetMessageType.DebugMessage:
					WriteToConsole(data.ReadString());
					break;
				case NetMessageType.StatusChanged:
					string statusMessage = data.ReadString();
					NetConnectionStatus newStatus = (NetConnectionStatus)data.ReadByte();
					WriteToConsole("New status: " + newStatus + " (" + statusMessage + ")");
					UpdateStatisticsDisplay(s_client.ServerConnection);
					break;
				case NetMessageType.Data:
					WriteToConsole("Message received: " + data);
					break;
				default:
					WriteToConsole("Unhandled: " + type);
					break;
			}
		}
Exemplo n.º 16
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");
		}
Exemplo n.º 17
0
 public void Read(NetBuffer im)
 {
     Address     = im.ReadString();
     ConnectName = im.ReadString();
     Information = im.ReadString();
 }
Exemplo n.º 18
0
		/// <summary>
		/// Handle incoming message
		/// </summary>
		private void HandleMessage(NetMessageType type, NetBuffer buffer)
		{
			switch (type)
			{
				case NetMessageType.DebugMessage:
					//
					// it's a library debug message; just display it in the console if debugger is attached
					//
					Console.WriteLine(buffer.ReadString());
					break;
				case NetMessageType.StatusChanged:
					//
					// it's a status change message; set the reason as window title and refresh picture
					//
					this.Text = buffer.ReadString();
					pictureBox1.Refresh();
					break;
				case NetMessageType.ServerDiscovered:
					//
					// it's a server discovered message; connect to the discovered server
					//
					m_imageWidth = 0;
					m_imageHeight = 0;
					m_lineDisplayed = 0;

					m_client.Connect(buffer.ReadIPEndPoint());
					break;
				case NetMessageType.Data:
					//
					// it's a data message (data sent from the server)
					//
					if (m_imageWidth == 0)
					{
						// first message is size
						m_imageWidth = (int)buffer.ReadVariableUInt32();
						m_imageHeight = (int)buffer.ReadVariableUInt32();
						this.Size = new System.Drawing.Size(m_imageWidth + 40, m_imageHeight + 60);
						pictureBox1.Image = new Bitmap(m_imageWidth, m_imageHeight);
						pictureBox1.SetBounds(12, 12, m_imageWidth, m_imageHeight);
						return;
					}

					uint pixelPos = buffer.ReadUInt32();

					// it's color data
					int y = (int)(pixelPos / m_imageWidth);
					int x = (int)(pixelPos - (y * m_imageWidth));

					Bitmap bm = pictureBox1.Image as Bitmap;
					pictureBox1.SuspendLayout();
					int pixels = (buffer.LengthBytes - 4) / 3;
					for (int i = 0; i < pixels; i++)
					{
						// set pixel
						byte r = buffer.ReadByte();
						byte g = buffer.ReadByte();
						byte b = buffer.ReadByte();
						Color col = Color.FromArgb(r, g, b);
						if (y > m_imageHeight)
							continue;
						bm.SetPixel(x, y, col);
						x++;
						if (x >= m_imageWidth)
						{
							x = 0;
							y++;
						}
					}
					pictureBox1.ResumeLayout();

					// refresh image every horizontal line
					if (pixelPos / m_imageWidth > m_lineDisplayed)
					{
						m_lineDisplayed = (int)(pixelPos / m_imageWidth);
						pictureBox1.Refresh();
					}
					break;
				default:
					// unhandled
					break;
			}
		}
Exemplo n.º 19
0
 public void Read(NetBuffer im)
 {
     Command = im.ReadString();
 }
Exemplo n.º 20
0
        public Packet GetPacket()
        {
            NetBuffer buf = new NetBuffer();
            NetMessageType type;
            NetConnection sender;
            IPEndPoint endpoint;

            if (server.ReadMessage(buf, out type, out sender, out endpoint))
            {
                switch (type)
                {
                    case NetMessageType.ConnectionApproval:
                        // Check if we are awainting a new connection:
                        int i;
                        for (i = 0; i < Server.Instance.clients.Count; i++)
                        {
                            // Got first packet from a known client?
                            if (IPEndPoint.Equals(Server.Instance.clients[i].netchan.remoteAddress, sender.RemoteEndpoint)
                                && Server.Instance.clients[i].netchan.incomingSequence == 0)
                            {
                                // Accept connection, and save NetConnection in netchan for later sending
                                Server.Instance.clients[i].netchan.connection = sender;
                                sender.Approve();
                                break;
                            }
                        }
                        // Client connection was not expected.. disapprove
                        if (i == Server.Instance.clients.Count)
                            sender.Disapprove("Not expecting this connection");
                        break;
                    case NetMessageType.StatusChanged:
                        // Lidgren network status messages
                        string str = buf.ReadString();
                        //Common.Instance.WriteLine(str);
                        break;
                    case NetMessageType.Data:
                    case NetMessageType.OutOfBandData:
                        return new Packet(buf, type, endpoint);
                    default:
                        str = buf.ReadString();
                        Common.Instance.WriteLine("Lidgren server: " + str);
                        break;
                }

            }
            if (client.ReadMessage(buf, out type, out endpoint))
            {
                switch (type)
                {
                    case NetMessageType.ConnectionRejected:
                        Client.Instance.state = ConnectState.DISCONNECTED;
                        string reason = buf.ReadString();
                        Common.Instance.WriteLine("Server rejected client connection: " + reason);
                        break;
                    case NetMessageType.StatusChanged:
                        string str = buf.ReadString();
                        if (str.Equals("Connected"))
                            IsClientConnected = true;
                        //Common.Instance.WriteLine(str);
                        break;
                    case NetMessageType.Data:
                    case NetMessageType.OutOfBandData:
                        return new Packet(buf, type, endpoint);
                    case NetMessageType.ServerDiscovered:
                        for (int i = 0; i < Client.Instance.localServers.Count; i++)
                        {
                            if (Client.Instance.localServers[i].adr == endpoint)
                                return null;
                        }
                        Common.Instance.WriteLine("Discovered lan server at {0}", endpoint);
                        Client.Instance.localServers.Add(new serverInfo_t() { adr = endpoint });
                        Client.Instance.HasNewServers = true;
                        break;
                    default:
                        str = buf.ReadString();
                        Common.Instance.WriteLine("Lidgren Client: " + str);
                        break;
                }

            }
            return null;
        }
Exemplo n.º 21
0
 public void Read(NetBuffer im)
 {
     MetaData    = im.ReadString();
     int l       = im.ReadInt32();
     Data        = im.ReadBytes(l);
 }
Exemplo n.º 22
0
 public static void DataHandler(NetClient client, NetBuffer buffer)
 {
     Console.WriteLine("Plugin: Data recieved");
     Console.WriteLine("Data: " + buffer.ReadString());
 }
Exemplo n.º 23
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();
        }
Exemplo n.º 24
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;
        }