Example #1
0
            public void run(int port)
            {
                TcpListener server = null;
                TcpClient   client = null;


                try
                {
                    server = new TcpListener(IPAddress.Any, port);
                    server.Start();
                    client = new TcpClient("localhost", port);
                    Socket serverSocket = server.AcceptSocket();
                    Socket clientSocket = client.Client;
                    sendSocket    = new StringSocket(serverSocket, new UTF8Encoding());
                    receiveSocket = new StringSocket(clientSocket, new UTF8Encoding());

                    mre1 = new ManualResetEvent(false);

                    receiveSocket.BeginReceive(CompletedReceive, 1);
                    sendSocket.BeginSend("Hêllø Ψórlđ!\n", (e, o) => { }, null);

                    Assert.AreEqual(true, mre1.WaitOne(timeout), "Timed out waiting");
                    // this will fail if the String Socket does not handle non-ASCII characters
                    Assert.AreEqual("Hêllø Ψórlđ!", msg);
                    System.Diagnostics.Debug.WriteLine(msg);
                    Assert.AreEqual(1, p1);
                }
                finally
                {
                    sendSocket.Close();
                    receiveSocket.Close();
                    server.Stop();
                    client.Close();
                }
            }
Example #2
0
        /// <summary>
        /// Receives commands from the players once the game is setup
        /// </summary>
        /// <param name="command">Command sent from player client</param>
        /// <param name="e">Exception</param>
        /// <param name="socketGameTuple">Tuple that contains the socket and the game object</param>
        private void CommandReceivedCallback(String command, Exception e, object socketGameTuple)
        {
            Tuple <Game, StringSocket> player = (Tuple <Game, StringSocket>)socketGameTuple;

            //If both the command and exception are null, one of the clients closed their connection
            if (command == null && e == null)
            {
                StringSocket p2 = (StringSocket)player.Item1.p2;
                StringSocket p1 = (StringSocket)player.Item1.p1;

                //Other player closed socket, send a message out and close the remaining socket
                if ((StringSocket)player.Item2 == (StringSocket)player.Item1.p1)
                {
                    p2.BeginSend("TERMINATED\n", (a, b) => { }, null);
                    p2.Close();
                }
                else
                {
                    p1.BeginSend("TERMINATED\n", (a, b) => { }, null);
                    p1.Close();
                }
            }

            lock (socketQueue)
            {
                if (command != null)
                {
                    //Game object needs to parse the command sent in
                    player.Item1.ParseCommand(command, player.Item2);

                    //Receive another line now that the command has been sent in
                    player.Item2.BeginReceive(CommandReceivedCallback, new Tuple <Game, StringSocket>(player.Item1, player.Item2));
                }
            }
        }
Example #3
0
        public void OpponentClosedGame()
        {
            BoggleServer.Server server = new BoggleServer.Server(2000, new string[] { "200", "Dictionary.txt" });

            mre1 = new ManualResetEvent(false);
            mre2 = new ManualResetEvent(false);

            //Separate MRE for the opponent closing test case
            opponentClosedMre = new ManualResetEvent(false);

            StringSocket client1 = Client.CreateClient(2000);

            client1.BeginSend("PLAY Testing1\n", (e, o) => { }, null);

            StringSocket client2 = Client.CreateClient(2000);

            client2.BeginSend("PLAY Testing2\n", (e, o) => { }, null);

            client1.BeginReceive(ReceiveClient1, "Client1");

            client2.BeginReceive(ReceiveClient2, "Client2");

            //Close the client and make sure the proper TERMINATED message is sent back
            Thread.Sleep(1000);
            client2.BeginReceive(OpponentClosedCallback, null);
            client1.Close();

            //Now make sure the remaining client gets the terminated message sent back
            Assert.AreEqual(true, opponentClosedMre.WaitOne(timeout), "Timed out waiting 3");
            Assert.AreEqual("TERMINATED", opponentClosedString);

            server.CloseServer();
        }
Example #4
0
        /// <summary>
        /// Disconnects the client from the boggle server, closes the socket connection
        /// </summary>
        public void Disconnect()
        {
            // closes the TcpClient
            client.Close();

            // closes the StringSocket
            socket.Close();
        }
        /// <summary>
        /// Requests a Connection from the server to the specified spreadsheet using the specified username.
        /// port and serverIP are the port and server IP address to connect to the server. e is the type of encoding
        /// that will be sent by the client.
        /// </summary>
        /// <param name="userName"></param>
        /// <param name="spreadsheetName"></param>
        public void connect(string userName, string spreadsheetName, int port, IPAddress serverIP, Encoding e)
        {
            //Disconnect the socket if it is not null.
            if (socket != null)
            {
                socket.Close();
            }

            //Connecting client to server and establishing a socket
            client = new TcpClient();
            client.Connect(serverIP, port);
            socket = new StringSocket(client.Client, e);

            //Start receiving server messages
            socket.BeginSend("connect " + userName + " " + spreadsheetName + "\n", (ee, pp) => { }, payload);
            socket.BeginReceive(serverMessages, payload);
        }
Example #6
0
        /// <summary>
        /// Checks to see if the user sent in the command PLAY (username)
        /// If so, sets the players name, if not, sends ignoring command back to the client
        /// </summary>
        /// <param name="name">Name the user sent in via Play command</param>
        /// <param name="e">Exception</param>
        /// <param name="p">Payload</param>
        private void PlayerNameReceived(String name, Exception e, object p)
        {
            StringSocket ss = (StringSocket)p;

            if (e != null || name == null)
            {
                //There's been an exception close the socket
                if (socketQueue.Count > 1)
                {
                    socketQueue.Dequeue();
                }
                ss.Close();
                return;
            }


            lock (socketQueue)
            {
                string[] command = name.Trim().Split(' ');

                //Make sure they sent in the PLAY command
                if (command[0].Equals("PLAY", StringComparison.InvariantCultureIgnoreCase))
                {
                    user_names.Enqueue(command[1]);
                    socketQueue.Enqueue(ss);
                }
                else
                {
                    ss.BeginSend("IGNORING " + command[0] + "\n", (a, b) => { }, null);
                    ss.BeginReceive(PlayerNameReceived, ss);
                    return;
                }

                //If there's another existing socket, pair them up in a game
                while (socketQueue.Count > 1)
                {
                    StringSocket player1 = socketQueue.Dequeue();
                    StringSocket player2 = socketQueue.Dequeue();

                    Game newGame;

                    Console.WriteLine("Game started");
                    //Checks to see if a board was passed in on command line, if not don't pass into Game class
                    if (gameBoard == null)
                    {
                        newGame = new Game(user_names.Dequeue(), user_names.Dequeue(), player1, player2, wordDic, time);
                    }
                    else
                    {
                        newGame = new Game(user_names.Dequeue(), user_names.Dequeue(), player1, player2, wordDic, time, gameBoard);
                    }

                    player1.BeginReceive(CommandReceivedCallback, new Tuple <Game, StringSocket>(newGame, player1));
                    player2.BeginReceive(CommandReceivedCallback, new Tuple <Game, StringSocket>(newGame, player2));
                }
            }
        }
Example #7
0
        public void Connect(String playerName, String ipAddress)
        {
            if (ss != null && ss.Connected)
            {
                ss.Close();
            }

            TcpClient tcpClient;

            try {
                tcpClient = new TcpClient(ipAddress, 2000);
                ss        = new StringSocket(tcpClient.Client, new UTF8Encoding());
            }
            catch (SocketException e) {
                Terminate(e.Message);
                return;
            }

            ss.BeginSend("PLAY " + playerName + "\n", (e, o) => { }, playerName);
            ss.BeginReceive(GameStarting, playerName);
        }
        /// <summary>
        /// Registers userName in server. Guarantees client username registration. Used if register fails.
        /// </summary>
        /// <param name="userName"></param>
        /// <param name="port"></param>
        /// <param name="serverIP"></param>
        /// <param name="e"></param>
        public static void registerUserAsAdmin(string userName, string spreadsheet, int port, IPAddress serverIP, Encoding e)
        {
            //Connecting client to server and establishing a socket
            TcpClient client = new TcpClient();

            client.Connect(serverIP, port);
            StringSocket socket = new StringSocket(client.Client, e);

            //Register userName using sysadmin workaround
            socket.BeginSend("connect sysadmin " + spreadsheet + "\n", (ee, pp) => { }, null);
            socket.BeginSend("register " + userName + "\n", (ee, pp) => { }, null);
            socket.Close();
            socket = null;
        }
Example #9
0
        /// <summary>
        /// Disconnects and closes the socket and TCPclient.  Activates an event
        /// that allows the GUI to reset things as needed when a disconnection happens.
        /// </summary>
        /// <param name="opponentDisconnected">Allows event to know if player
        ///                                    disconnected or opponent disconnected.</param>
        public void Terminate(bool opponentDisconnected)
        {
            if (socket != null)
            {
                socket.Close();
            }
            if (client != null)
            {
                client.Close();
            }

            if (!playerDisconnected)
            {
                DisconnectOrErrorEvent(opponentDisconnected);
            }
        }
Example #10
0
        public void TestCloseBasic()
        {
            TcpListener server = new TcpListener(IPAddress.Any, 4006);

            server.Start();
            TcpClient client = new TcpClient("localhost", 4006);

            Socket serverSocket = server.AcceptSocket();
            Socket clientSocket = client.Client;

            StringSocket sendSocket    = new StringSocket(serverSocket, new UTF8Encoding());
            StringSocket receiveSocket = new StringSocket(clientSocket, new UTF8Encoding());

            sendSocket.Close();
            receiveSocket.Close();

            bool test1 = serverSocket.Available == 0; //Should fail here because socket should be shutdown and closed
        }
Example #11
0
        /// <summary>
        /// Retrieves the HTTP Request and finds the html to send back in response
        /// </summary>
        /// <param name="request">The request sent in</param>
        /// <param name="e">Possible Exception</param>
        /// <param name="payload">Payload</param>
        private void HttpRequestReceived(string request, Exception e, object payload)
        {
            StringSocket connectionSocket = (StringSocket)payload;
            string       httpResponse     = "HTTP/1.1 200 OK\r\nConnection: close\r\nContent-Type: text/html; charset=UTF-8\r\n";

            if (request != null && Regex.IsMatch(request, @"^GET"))
            {
                string[] splitRequest = request.Split(' ');

                string htmlFiller = HtmlForPage(splitRequest[1]);
                string html       = String.Format(@"<html>
                                                <head><title>Boggle</title></head>
                                                <body><h1>BEST BOGGLE SITE EVER</h1><br/><a href='/players'>Home</a><br/>{0}</body>
                                                </html>", htmlFiller);

                connectionSocket.BeginSend(httpResponse, (a, b) => { }, null);
                connectionSocket.BeginSend("\r\n", (a, b) => { }, null);
                connectionSocket.BeginSend(html, (a, b) => { }, null);
            }

            connectionSocket.Close();
        }
 /// <summary>
 /// Closes stuff down
 /// </summary>
 private static void CloseSockets(StringSocketListener server, StringSocket s1, SS s2)
 {
     try
     {
         s1.Shutdown(SocketShutdown.Both);
     }
     finally
     {
     }
     try
     {
         s2.Shutdown(SocketShutdown.Both);
     }
     finally
     {
     }
     try
     {
         s1.Close();
     }
     finally
     {
     }
     try
     {
         s2.Close();
     }
     finally
     {
     }
     try
     {
         server.Stop();
     }
     finally
     {
     }
 }
Example #13
0
        private void GetReceived(string s, Exception e, object payload)
        {
            StringSocket ss = (StringSocket)payload;


            //check for errors / lost connection
            if (payload == null)
            {
                return;
            }
            if (e != null)
            {
                return;
            }
            if (s.StartsWith("GET /players HTTP/1.1"))
            {
                sendString.Append("<h1>Players Page</h1><table border =\"1\">");
                sendString.Append(getTableHeader("players"));

                sendString.Append(GetPlayersPage());
                ss.BeginSend(sendString.ToString(), (ee, oo) => { }, ss);
                sendString.Clear();
            }
            else if (s.StartsWith("GET /games?player="))
            {
                //get name
                s = s.Substring(18);
                s = s.Substring(0, s.IndexOf(" "));

                sendString.Append("<h1>Player Page</h1><table border =\"1\">");
                sendString.Append(getTableHeader("player"));

                sendString.Append(GetPlayerInfo(s));
                sendString.Append("</table>");
                sendString.Append("</html>");
                ss.BeginSend(sendString.ToString(), (ee, oo) => { }, ss);
                sendString.Clear();
            }
            else if (s.StartsWith("GET /game?id="))
            {
                s = s.Substring(13);
                s = s.Substring(0, s.IndexOf(" "));
                int id = 0;
                if (int.TryParse(s, out id))
                {
                    sendString.Append("<h1>Game Page</h1><table border =\"1\">");
                    sendString.Append(getTableHeader("game"));

                    sendString.Append(GetGameInfo(id));
                    sendString.Append("</table>");
                    sendString.Append("</html>");

                    ss.BeginSend(sendString.ToString(), (ee, oo) => { }, ss);
                    sendString.Clear();
                }
                else
                {
                    sendString.Append("<h1>The URL that you entered was invalid</h1>" +
                                      "<H3>Please try one of the following options:</h3>" +
                                      "<p>for players win, loss and tie information enter <bold>http://localhost:2500/players</bold>" +
                                      "<p>for Individual player information enter <bold>http://localhost:2500/games?player=name</bold> where name is the name of the player" +
                                      "<p>for Individual game information enter <bold>http://localhost:2500/game?id=number</bold> where number is an int that identifies that game" +
                                      "</html>");
                    ss.BeginSend(sendString.ToString(), (ee, oo) => { }, ss);
                    sendString.Clear();
                }
            }
            else
            {
                sendString.Append("<h1>The URL that you entered was invalid</h1>" +
                                  "<H3>Please try one of the following options:</h3>" +
                                  "<p>for players win, loss and tie information enter <b>http://localhost:2500/players</b>" +
                                  "<p>for Individual player information enter <b>http://localhost:2500/games?player=name</b> where name is the name of the player" +
                                  "<p>for Individual game information enter <b>http://localhost:2500/game?id=number</b> where number is an int that identifies that game" +
                                  "</html>");
                ss.BeginSend(sendString.ToString(), (ee, oo) => { }, ss);
                sendString.Clear();
            }

            ss.Close();
        }
Example #14
0
 /// <summary>
 /// close the underlying socket
 /// </summary>
 public void closeSocket()
 {
     socket.Close();
 }
Example #15
0
 /// <summary>
 /// Disconnects the current client model from the server.
 /// </summary>
 public void disconnect()
 {
     socket.Close();
 }
Example #16
0
        /// <summary>
        /// This method is the event that happens each time a second passes with the interval timer
        /// </summary>

        private void OneSecondPasses(Object source, ElapsedEventArgs e)
        {
            // Each time a second passes, time is reduced by 1
            time--;

            int p1Id = 0;
            int p2Id = 0;
            int gId;


            p1.BeginSend("TIME " + time + '\n', (a, b) => { }, null);
            p2.BeginSend("TIME " + time + '\n', (a, b) => { }, null);

            // When time reaches zero, sends final score and final message
            if (time == 0)
            {
                if (p1.Connected == true && p2.Connected == true)
                {
                    // These variables are declared in here, as if they were declared
                    // outside of the if statement, then they would be declared and set
                    // each time the interval timer called this event, wasting system resources.
                    // These are strings that will hold the words from each of the hash sets, with
                    // spaces in between each word
                    string p1PlayedWords  = "";
                    string p2PlayedWords  = "";
                    string commonWords    = "";
                    string p1IllegalWords = "";
                    string p2IllegalWords = "";

                    // Sets the interval timer enabled flag to false
                    secondTimer.Enabled = false;

                    // Sends the final score
                    p1.BeginSend("SCORE " + p1Score + " " + p2Score + "\n", (a, b) => { }, false);
                    p2.BeginSend("SCORE " + p2Score + " " + p1Score + "\n", (a, b) => { }, false);


                    // foreach loop to conver the hashet for p2 legal words into a string of all the words separated by a comma
                    foreach (string word in p1Words)
                    {
                        p1PlayedWords = p1PlayedWords + word + " ";
                    }

                    // foreach loop to convert the hashset for p2 legal words into a string of all the words separated by a comma
                    foreach (string word in p2Words)
                    {
                        p2PlayedWords = p2PlayedWords + word + " ";
                    }

                    // foreach loop to convert the hashset for words played in common into a string of all the words separated by a comma
                    foreach (string word in playedWords)
                    {
                        commonWords = commonWords + word + " ";
                    }

                    // foreach loop to convert the hashset for p1 illegal words into a string of all the words separated by a comma
                    foreach (string word in p1Illegal)
                    {
                        p1IllegalWords = p1IllegalWords + word + " ";
                    }

                    // foreach loop to convert the hashset for p2 illegal words into a string of all the words separated by a comma
                    foreach (string word in p2Illegal)
                    {
                        p2IllegalWords = p2IllegalWords + word + " ";
                    }

                    // Sends the final message. Final message includes "STOP" command, and then
                    p1.BeginSend("STOP " + p1Words.Count + " " + p1PlayedWords.Trim() + " " + p2Words.Count + " " + p2PlayedWords.Trim() + " " + playedWords.Count + " " + commonWords.Trim() + " " + p1Illegal.Count + " " + p1IllegalWords.Trim() + " " + p2Illegal.Count + " " + p2IllegalWords.Trim() + "\n", (a, b) => { }, true);
                    p2.BeginSend("STOP " + p2Words.Count + " " + p2PlayedWords.Trim() + " " + p1Words.Count + " " + p1PlayedWords.Trim() + " " + playedWords.Count + " " + commonWords.Trim() + " " + p2Illegal.Count + " " + p2IllegalWords.Trim() + " " + p1Illegal.Count + " " + p1IllegalWords.Trim() + "\n", (a, b) => { }, true);



                    //Database connection
                    string connectionString = "server=atr.eng.utah.edu;database=cs3500_weeter;uid=cs3500_weeter;password=984751090;Convert Zero Datetime=True";

                    // Connect to the DB
                    using (MySqlConnection conn = new MySqlConnection(connectionString))
                    {
                        try
                        {
                            conn.Open();

                            // Create a command
                            MySqlCommand command = conn.CreateCommand();


                            // Object to get the data
                            object queryReturn;

                            // Command to select the pId
                            command.CommandText = String.Format("SELECT pId FROM Players WHERE playerName= '{0}'", p1Name);
                            queryReturn         = command.ExecuteScalar();

                            // If query is null, inserts the player
                            if (queryReturn == null)
                            {
                                command.CommandText = String.Format("INSERT INTO Players (playerName) VALUES ('{0}')", p1Name);
                                command.ExecuteNonQuery();
                            }



                            // Attempts to select the ID for player 2
                            command.CommandText = String.Format("SELECT pId FROM Players WHERE playerName= '{0}'", p2Name);
                            queryReturn         = command.ExecuteScalar();

                            // If not, inserts player 2
                            if (queryReturn == null)
                            {
                                command.CommandText = String.Format("INSERT INTO Players (playerName) VALUES ('{0}')", p2Name);
                                command.ExecuteNonQuery();
                            }

                            // Gets the pID for both players
                            command.CommandText = String.Format("SELECT pId FROM Players WHERE playerName= '{0}'", p1Name);
                            queryReturn         = command.ExecuteScalar();


                            int.TryParse(queryReturn.ToString(), out p1Id);


                            command.CommandText = String.Format("SELECT pId FROM Players WHERE playerName= '{0}'", p2Name);
                            queryReturn         = command.ExecuteScalar();

                            int.TryParse(queryReturn.ToString(), out p2Id);



                            // Formats the date into something mySql can use
                            string formatForMySql = DateTime.Now.ToString("yyyy-MM-dd HH:mm:ss");

                            // Inserts the game data into the game table
                            command.CommandText = String.Format("INSERT INTO Games (p1Id, p2Id, p1Score, p2Score, board, gameEnded, timeLimit) VALUES ('{0}', '{1}', '{2}', '{3}', '{4}', '{5}', '{6}')", p1Id, p2Id, p1Score, p2Score, board, formatForMySql, timeGame);
                            command.ExecuteNonQuery();

                            // Gets the game ID
                            command.CommandText = String.Format("SELECT LAST_INSERT_ID()");
                            queryReturn         = command.ExecuteScalar();

                            // If the game ID was not successfully received, throws an exception
                            if (queryReturn != null)
                            {
                                int.TryParse(queryReturn.ToString(), out gId);
                            }
                            else
                            {
                                throw new Exception("Problem getting game ID from Database");
                            }



                            // foreach loop to convert the hashset for p1 legal words into a string of all the words separated by a comma
                            foreach (string word in p1Words)
                            {
                                command.CommandText = String.Format("INSERT INTO Words (gId, word, pId, legal) VALUES ('{0}', '{1}', '{2}', '{3}')", gId, word, p1Id, 1);
                                command.ExecuteNonQuery();
                            }

                            // foreach loop to convert the hashset for p2 legal words into a string of all the words separated by a comma
                            foreach (string word in p2Words)
                            {
                                command.CommandText = String.Format("INSERT INTO Words (gId, word, pId, legal) VALUES ('{0}', '{1}', '{2}', '{3}')", gId, word, p2Id, 1);
                                command.ExecuteNonQuery();
                            }

                            // foreach loop to convert the hashset for words played in common into a string of all the words separated by a comma
                            foreach (string word in playedWords)
                            {
                                command.CommandText = String.Format("INSERT INTO Words (gId, word, pId, legal) VALUES ('{0}', '{1}', '{2}', '{3}')", gId, word, p1Id, 1);
                                command.ExecuteNonQuery();

                                command.CommandText = String.Format("INSERT INTO Words (gId, word, pId, legal) VALUES ('{0}', '{1}', '{2}', '{3}')", gId, word, p2Id, 1);
                                command.ExecuteNonQuery();
                            }

                            // foreach loop to convert the hashset for p1 illegal words into a string of all the words separated by a comma
                            foreach (string word in p1Illegal)
                            {
                                command.CommandText = String.Format("INSERT INTO Words (gId, word, pId, legal) VALUES ('{0}', '{1}', '{2}', '{3}')", gId, word, p1Id, 0);
                                command.ExecuteNonQuery();
                            }

                            // foreach loop to convert the hashset for p2 illegal words into a string of all the words separated by a comma
                            foreach (string word in p2Illegal)
                            {
                                command.CommandText = String.Format("INSERT INTO Words (gameId, word, pId, legal) VALUES ('{0}', '{1}', '{2}', '{3}')", gId, word, p2Id, 0);
                                command.ExecuteNonQuery();
                            }


                            // This thread sleep allows gives the client adequate time to get the message before closing the clients
                            System.Threading.Thread.Sleep(1000);

                            // Closes the sockets after the final message has been terminated
                            p1.Close();
                            p2.Close();
                        }
                        catch (Exception ex)
                        {
                            Console.WriteLine(ex.Message);
                        }
                    }
                }
            }
        }