예제 #1
0
        public static void Start()
        {
            // Start the network discovery server.
            HelloPacket hello     = new HelloPacket("server", Networking.getExternalIPE(), port);
            Thread      udpserver = new Thread(() => StartListener(hello));

            udpserver.Start();

            Console.WriteLine("Length of Hostlist: {0}", hostList.ToArray().Length);

            Console.WriteLine("Press any key to start the server");
            Console.ReadKey();

            // Start the Tcp Server and send the first tater
            // IP_Tato tater = new IP_Tato("Tater #1", 5);

            Thread[] taterThreadList = new Thread[taterMaxNumber];
            for (int x = 0; x < taterThreadList.Length; x++)
            {
                Console.WriteLine("Creating IP_Tato server {0}", x + 1);
                IP_Tato tater = new IP_Tato("Tater #" + x, 5);
                taterThreadList[x] = new Thread(() => ServerTest(tater));
                taterThreadList[x].Start();
            }

            // Thread tcpserver = new Thread(() => ServerTest(tater));
            // tcpserver.Start();
        }
예제 #2
0
        private void btn_TestTater(object sender, RoutedEventArgs e)
        {
            IP_Tato tater = new IP_Tato();

            tater.Explode();

            Task showDialogBox = Task.Run(() => {
                // This will update the GUI with the results of the tater
                EventWaitHandle ewh = new EventWaitHandle(false, EventResetMode.ManualReset);

                Application app = Application.Current;
                app.Dispatcher.Invoke((Action) delegate {
                    Game_Popup game_Popup = new Game_Popup(tater);
                    // Try to update GUI from this thread.


                    // The ShowDialog is the perfect function for this.
                    // It blocks until the window is closed which is all I needed it to do.
                    game_Popup.Show();

                    // If I can Wait outside of this dispatcher, then it should be best
                    game_Popup.Closing += (object send, System.ComponentModel.CancelEventArgs eargs) => { ewh.Set(); };
                });
                // Event Listener
                ewh.WaitOne();

                // Timeout check

                // Return whether the potato was requested to be passed.
                return(true);
            });

            Console.WriteLine("The Popup has completed its task.");
        }
예제 #3
0
        public Game_Popup(IP_Tato tater)
        {
            InitializeComponent();
            this.DataContext = this;
            string Popup_Title = $"IP_Tato - {tater.TargetClient.hostname}";

            this.Title = Popup_Title;

            string  whoSentText       = $"{tater.LastClient.hostname} has sent you a Hot IP_Tato";
            Binding bind_WhoSentTater = new Binding();

            bind_WhoSentTater.Source = whoSentText;
            txtWhoSentTater.SetBinding(TextBlock.TextProperty, bind_WhoSentTater);

            if (tater.Exploded)
            {
                Binding bind_imgPotato = new Binding();
                bind_imgPotato.Source = "img/exploded-potato-edit.jpg";
                imgPotato.SetBinding(Image.SourceProperty, bind_imgPotato);

                string  bind_btnPassPotato   = "Darn";
                Binding btnPassPotatoBinding = new Binding();
                btnPassPotatoBinding.Source = bind_btnPassPotato;
                btnPassPotato.SetBinding(Button.ContentProperty, btnPassPotatoBinding);
            }

            // Push the popup to the front.
            this.Topmost = true;
        }
예제 #4
0
        public void Add_IP_Tato()
        {
            int     numberOfClients = HostList.ToArray().Length;
            IP_Tato tater           = new IP_Tato("Tater #" + IP_TatoID++, Utilities.RandomInteger(numberOfClients, numberOfClients * 2));
            Thread  newTaterThread  = new Thread(() => IP_TatoHandler(tater));

            newTaterThread.IsBackground = true;
            newTaterThread.Start();
            IP_TatoThreads.Add(newTaterThread);
        }
예제 #5
0
        private static object ProcessPotato(object obj)
        {
            // Some of these commands should be placed in the potato object
            //  Because they then can be protected

            // Create IP_Tato
            IP_Tato tater = obj as IP_Tato;


            // Add the current host to the holderHistory
            // This is done on the client side for pessimism's sake
            // tater.AddCurrentHostToHolderHistory();
            // Instead set the previous client to self
            tater.LastClient = tater.TargetClient;

            // Pseudocode
            // Check Flags of tater
            // Do stuff according to the flags on tater
            // Flags are stored as bools and should be assigned by
            // * names rather than position.
            // Flag Precedence is a thing a potato should explode before other things happen.

            // Print last player that tater was passed from
            // "$player passed a potato to you"


            // Check if number of passes is done.
            // Greater than used to catch too many passes.
            if (tater.Passes == 0)
            {
                tater.Explode();
            }
            // This will update the GUI with the results of the tater
            Application app = Application.Current;

            if (app == null)
            {
                Main();
                app = Current;
            }
            app.Dispatcher.Invoke((Action) delegate {
                // Try to update GUI from this thread.
                Game_Popup game_Popup = new Game_Popup(tater);

                // The ShowDialog is the perfect function for this.
                // It blocks until the window is closed which is all I needed it to do.
                game_Popup.ShowDialog();
            });
            // Increment current passes
            // This is done at the end in case of an involuntary host disconnect
            tater.Passes--;

            return(tater as object);
        }
예제 #6
0
        private HelloPacket RouteIP_Tato(IP_Tato tater)
        {
            // TODO add different routing techniques
            int rolls = 0;

            HelloPacket[] hostArray = HostList.ToArray();
            do
            {
                int index = Utilities.RandomInteger(0, hostArray.Length);
                tater.TargetClient = hostArray[index];
                rolls++;
            }while (tater.TargetClient.address == tater.LastClient.address);

            Console.WriteLine("Previous Client: {0}", tater.LastClient.address);
            Console.WriteLine("New targetClient {0} chosen after {1} roll(s)", tater.TargetClient, rolls);
            return(tater.TargetClient);
        }
예제 #7
0
        /// <summary>
        /// This is meant to Manage the IP_Tato either as an object that can be returned
        ///   Or just a function to take care of the logic of the potato.
        /// </summary>
        /// <param name="tater"></param>
        private void IP_TatoHandler(IP_Tato tater)
        {
            //TODO: Finish translating what is in PassDataToClient into this function.
            tater.LastClient = HostInformation;
            while (tater.Passes > 0)
            {
                // Select the target client
                tater.TargetClient = RouteIP_Tato(tater);

                Console.WriteLine("The new targetClient is: {0}", tater.TargetClient);
                // Set up the target address
                IPEndPoint targetClient = tater.TargetClient.EndPoint();
                // Pass data to be sent to client
                // This function returns the response data from the client.
                object responseObject = PassDataToClient(tater, targetClient);

                if (responseObject is IP_Tato)
                {
                    // Do stuff with the tater (probably reroute)
                    tater = responseObject as IP_Tato;
                    if (tater.Exploded)
                    {
                        Console.WriteLine("Tater has exploded \n removing client from Hostlist.");
                        this.KickPlayer(tater.TargetClient);
                        //OnRaiseClientDisconnectedEvent(tater.TargetClient);
                    }
                }
                else if (responseObject is string)
                {
                    switch ((string)responseObject)
                    {
                    case "CMD:Disconnect":
                        this.KickPlayer(tater.TargetClient);
                        break;

                    case "RESPONSE:Disconnect":
                        OnRaiseClientDisconnectedEvent(tater.TargetClient);
                        break;
                    }
                    // Right now the only string that will be returned is that the client refused the tater.
                }

                // Verify the current state is correct
                Console.WriteLine("Server received: {0}", tater.ToString());
            }
        }
예제 #8
0
        private static void Test()
        {
            Console.WriteLine("\n\nTesting the Program:");
            int udpClientNum = 2;
            // Start up the server thread.
            HelloPacket hello1     = new HelloPacket("server", "127.0.0.1", port);
            Thread      udpserver1 = new Thread(() => StartListener(hello1));

            udpserver1.Start();

            // Start up the UDP client threads
            Thread[] clientThreadList = new Thread[listenerMaxNumber];
            for (int x = 0; x < clientThreadList.Length; x++)
            {
                Console.WriteLine("Creating UDP Client {0}", x + 1);
                HelloPacket clientInfo = new HelloPacket($"client {x + 1}", $"127.0.0.{udpClientNum}", port);
                Console.WriteLine($"UDP Client Created: {clientInfo.ToString()}");
                clientThreadList[x] = new Thread(() => StartBroadcast(clientInfo));
                clientThreadList[x].IsBackground = true;
                clientThreadList[x].Start();
                Console.WriteLine("Creating TCP Client {0}", x + 1);
                clientThreadList[x] = new Thread(() => CallListenerTest(clientInfo));
                clientThreadList[x].IsBackground = true;
                clientThreadList[x].Start();
                udpClientNum++;
            }


            // Test the Client and Listener Threads

            Console.WriteLine("Press any key to start the taters...");
            Console.ReadKey();

            Thread[] taterThreadList = new Thread[taterMaxNumber];
            for (int x = 0; x < taterThreadList.Length; x++)
            {
                Console.WriteLine("Creating IP_Tato server {0}", x + 1);
                IP_Tato tater = new IP_Tato("Tater #" + x, 5);
                taterThreadList[x] = new Thread(() => ServerTest(tater));
                taterThreadList[x].Start();
            }
        }
예제 #9
0
        public static void TestTater()
        {
            // Test IP_Tato Object
            Console.WriteLine("Test the IP_Tato");
            IP_Tato tater = new IP_Tato("Tater", 5);

            Console.WriteLine("Hot IP_Tato Object:");
            Console.WriteLine(tater.ToString());

            // Test the methods within the tater
            // tater.TestMethods();

            // Serialization Test
            Console.WriteLine("Testing Serialization and Deserialization.");
            Message serializedTater = Utilities.Serialize(tater);

            Console.WriteLine("Serialized Tater: {0}", serializedTater);
            Console.WriteLine("Size of the serialized object: {0} bytes", serializedTater.data.Length);

            IP_Tato newTater = new IP_Tato();

            newTater = (IP_Tato)Utilities.Deserialize(serializedTater);
            Console.WriteLine("Deserialized Tater: {0}", newTater.ToString());
        }
예제 #10
0
        private static object ProcessPotato(object obj)
        {
            // Some of these commands should be placed in the potato object
            //  Because they then can be protected

            // Create IP_Tato
            IP_Tato tater = obj as IP_Tato;

            // Increment current passes
            tater.Passes--;

            // Add the current host to the holderHistory
            // This is done on the client side for pessimism's sake
            // tater.AddCurrentHostToHolderHistory();
            // Instead set the previous client to self
            tater.LastClient = tater.TargetClient;

            // Pseudocode
            // Check Flags of tater
            // Do stuff according to the flags on tater
            // Flags are stored as bools and should be assigned by
            // * names rather than position.
            // Flag Precedence is a thing a potato should explode before other things happen.

            // Print last player that tater was passed from
            // "$player passed a potato to you"


            // Check if number of passes is done.
            // Greater than used to catch too many passes.
            if (tater.Passes == 0)
            {
                tater.Explode();
            }
            return(tater as object);
        }
예제 #11
0
        // This listener will basically function as the client for most intents and purposes.
        public static void CallListenerTest(HelloPacket clientInfo)
        {
            TcpListener listener = null;

            try
            {
                Console.WriteLine("IP is {0}", clientInfo.address);
                IPAddress localip = IPAddress.Parse((clientInfo.address));
                Console.WriteLine("Starting a tcplistener at {0} using port {1}", localip, clientInfo.port);
                listener = new TcpListener(localip, clientInfo.port);
                listener.Start();
                Console.WriteLine("Listener has started.");

                // Create Buffer
                byte[] buffer = new byte[buffersize];

                while (true)
                {
                    // Add an extra space to help distinguish between each server transaction.
                    Console.WriteLine();
                    Console.WriteLine("Client wating for a connection... ");

                    // Accept a pending connection
                    TcpClient client = listener.AcceptTcpClient();
                    Console.WriteLine("Connected!");

                    // Instantiate the stream
                    NetworkStream stream = client.GetStream();

                    // While there is data to be read
                    // TODO: Implement the ability to read more data with a smaller buffer.
                    while ((stream.Read(buffer, 0, buffer.Length)) != 0)
                    {
                        try
                        {
                            // Instantiate a Message object to hold the incoming object
                            Message incomingMessage = new Message();
                            // Assign the data which has been read to incomingMessage
                            incomingMessage.data = buffer;
                            // Deserialize the inbound data into an object which can be processed
                            //   By the function or workerthread.
                            IP_Tato receivedTato = Utilities.Deserialize(incomingMessage) as IP_Tato;
                            // Verify that the server received the correct data
                            Console.WriteLine("Client Received: " + receivedTato.ToString());

                            Console.WriteLine("Processing Request...");

                            // TODO: Create a worker thread to work with the potato.
                            //      This will be especially necessary when UI gets involved.
                            // For now it is just going to call a function
                            IP_Tato objectResponse = (IP_Tato)ProcessPotato(receivedTato);

                            if (objectResponse.Exploded)
                            {
                                // Exact the consequences of an exploded tater
                            }
                            else
                            {
                                Console.WriteLine($"You have received an IP_Tato from {receivedTato.LastClient}");
                                Console.WriteLine("Press any key to send the tater back!");
                                Console.ReadKey();
                            }

                            // Instantiate a Message to hold the response message
                            Message responseMessage = new Message();
                            responseMessage = Utilities.Serialize(objectResponse);

                            // Send back a response.
                            stream.Write(responseMessage.data, 0, responseMessage.data.Length);
                            // Verify that the data sent against the client receipt.
                            Console.WriteLine("Client Sent {0}", objectResponse.ToString());
                        }
                        catch (Exception ErrorProcessRequest)
                        {
                            Console.WriteLine("The request failed to be processed. Error details: " + ErrorProcessRequest);
                        }



                        // byte[] msg = System.Text.Encoding.ASCII.GetBytes("Server Received: " + data.ToString());
                    }
                    Console.WriteLine("---Listener Transaction Closed---");
                    stream.Close();
                    client.Close();
                }
            }
            catch (SocketException e)
            {
                Console.WriteLine("Server SocketException: {0}", e);
            }
            finally
            {
                listener.Stop();
            }
        }
예제 #12
0
        private static void ServerTest(IP_Tato tater)
        {
            // TODO Add in a test over a network connection (to verify how much it can handle)
            // TODO Figure out how to negate Denial of Service Attacks.

            // Add in tater stuff

            // Each instance of this method handles just one tater until it's lifetime expires
            // So then really this function is more like a StartTato() method.
            // Especially once potato routing is a thing. - It is a thing now.

            // When this all is converted to be OOP, then hostlist may become a part of the server class

            // for (int x = 1; x < listenerMaxNumber + 1; x++)
            // {
            //    string tempip = "127.0.0." + x;
            //    Console.WriteLine("Adding {0} to hostList", tempip);
            //    hostList.Add(tempip);
            //}



            while (tater.Passes > 0)
            {
                // Choose a targetClient
                tater.TargetClient = RouteTater(hostList, tater.LastClient);

                Console.WriteLine("The new targetClient is: {0}", tater.TargetClient);



                // Set the values which will be used for each connection
                IPAddress  serveraddress = IPAddress.Parse(tater.TargetClient.address);
                int        port          = 13000;
                IPEndPoint server        = new IPEndPoint(serveraddress, port);

                TcpClient client = new TcpClient();

                // Initialize the retry counter (which may be overkill)
                int retries;
                for (retries = 0; retries < 5; retries++)
                {
                    // Handle unseen errors
                    try
                    {
                        // Connect to the server
                        client.Connect(server);

                        // Serialize the object which will be sent
                        Message outboundMessage = Utilities.Serialize(tater);

                        // Initialize the stream
                        NetworkStream stream = client.GetStream();

                        // Send the object through the stream
                        Console.WriteLine("Server Sent {0} bytes.", outboundMessage.data.Length);
                        stream.Write(outboundMessage.data);
                        Console.WriteLine("Server Sent: {0} \n Retry #: {1}", tater.ToString(), retries);

                        // -- Part 2: Receive the response. --

                        // Create a Message object to receive the response
                        // Create Buffer
                        // The size of the buffer will need to be adapted to the
                        // Size of the IP_Tato object. --- Until I make a dynamic buffer
                        Message inboundMessage = new Message(buffersize);

                        // This reads the server's response from the network
                        // It assigns the response byte [] to the buffer.
                        int bytes = stream.Read(inboundMessage.data, 0, inboundMessage.data.Length);

                        if (inboundMessage.Equals(0))
                        {
                            Console.WriteLine("Received an empty message");
                        }

                        // Deserialize the data which was received and create a tater
                        object responseData = Utilities.Deserialize(inboundMessage) as object;
                        tater = responseData as IP_Tato;
                        // Verify the current state is correct
                        Console.WriteLine("Server received: {0}", tater.ToString());



                        // Close out the connection
                        stream.Close();
                        Console.WriteLine("---Server Transaction Closed---");
                        if (tater.Passing == false)
                        {
                            Console.WriteLine($"{tater.TargetClient} has disconnected");
                            hostList.Remove(tater.TargetClient);
                            continue;
                        }
                        // Break out of the retry loop.
                        break;
                    }
                    catch (ArgumentNullException e)
                    {
                        Console.WriteLine("Server ArgumentNullException: {0}", e);
                        continue;
                    }
                    catch (SocketException e)
                    {
                        Console.WriteLine("Server SocketException: {0}", e);
                        continue;
                    }
                }
                client.Close();
            }
            Console.WriteLine("The IP_Tato {0} has exploded.", tater.Name);
        }
예제 #13
0
        private object ProcessRequest(object receivedObject)
        {
            object objectResponse = "ERR:ProcessFailure";

            if (receivedObject is IP_Tato)
            {
                // Process the IP_Tato
                IP_Tato tater = receivedObject as IP_Tato;
                tater.Passes--;


                // Check if tater has exploded
                if (tater.Passes == 0)
                {
                    tater.Explode();
                    objectResponse = tater;
                    // OnRaiseClientDisconnectedEvent(ClientInfo);
                }


                // Set up a EventWaitHandle to block code execution until the popup is closing.
                EventWaitHandle ewh           = new EventWaitHandle(false, EventResetMode.ManualReset);
                bool            taterIsPassed = false;

                // Update the GUI with the results of the tater
                Application app = Application.Current;
                app.Dispatcher.Invoke((Action) delegate
                {
                    // Create a new popup
                    Game_Popup game_Popup = new Game_Popup(tater);

                    // Show the popup
                    game_Popup.Show();



                    // Set up an event handler to capture the results of the popup
                    game_Popup.Closing += (object send, System.ComponentModel.CancelEventArgs eargs) =>
                    {
                        taterIsPassed = game_Popup.Passing;
                        ewh.Set();
                    };
                });
                if (tater.Exploded)
                {
                    ewh.Set();
                    for (int x = 0; x < 10; x++)
                    {
                        app.Dispatcher.Invoke((Action) delegate
                        {
                            // Create a new popup
                            Game_Popup game_Popup = new Game_Popup(tater);

                            // Show the popup
                            game_Popup.Show();
                        });
                    }
                    // OnRaiseClientDisconnectedEvent(ClientInfo);
                }
                // Block until the popup closing event fires.
                ewh.WaitOne();
                if (taterIsPassed || tater.Exploded)
                {
                    // Set the previous client to the current client.
                    tater.LastClient = tater.TargetClient;
                    objectResponse   = tater;
                }
                else
                {
                    OnRaiseClientDisconnectedEvent(ClientInfo);
                    objectResponse = "RESPONSE:Disconnect";
                }
            }

            return(objectResponse);
        }