コード例 #1
0
ファイル: Client.cs プロジェクト: unaveed/Spreadsheet
        /// <summary>
        /// Connect to the server at the given hostname and port and with the given name of username and
        /// password.
        /// </summary>
        public bool Connect(String hostname, int port, String password)
        {
            try
            {
                TcpClient client;
                //Case 1: Using IP
                IPAddress address;
                if (IPAddress.TryParse(hostname, out address))
                {
                    client = new TcpClient();
                    client.Connect(address, port);
                }
                else
                {
                    //Case 2: Using DNS
                    client = new TcpClient(hostname, port);
                }

                socket = new StringSocket(client.Client, UTF8Encoding.Default);
                //PASSWORD[esc]password\n
                char esc = (char)27;
                socket.BeginSend("PASSWORD" + esc + password + "\n", (e, p) => { }, null);
                socket.BeginReceive(LineReceived, null);

                return true;
            }
            catch
            {
                return false;
            }
        }
コード例 #2
0
        /// <summary>
        /// Deal with an arriving line of text.
        /// </summary>
        private void LineReceived(String s, Exception e, object p)
        {
            // E and S will come back null when we close our socket
            if (ReferenceEquals(e, null) && ReferenceEquals(s, null) || !ReferenceEquals(e, null))
            {
                return;
            }

            // If we've been terminated, then reset everything and inform user
            if (s == "TERMINATED")
            {
                _stringSocket.Close();
                _stringSocket = null;
            }

            // Send the line onward if the connection was not terminated
            if (IncomingLineEvent != null)
            {
                IncomingLineEvent(s);
            }

            // Start listening on the socket again
            if (!ReferenceEquals(_stringSocket, null))
            {
                _stringSocket.BeginReceive(LineReceived, null);
            }

        }
コード例 #3
0
 /// <summary>
 /// Creates an ALREADY CONNECTED client model.
 /// </summary>
 public ChatClientModel(Socket s) {
     
         socket = new StringSocket(s, UTF8Encoding.Default);
         socket.BeginReceive(LineReceived, null);
         connected = true;
     
 }
コード例 #4
0
        public void TestBasicWord()
        {
            TcpListener server = null;
            TcpClient client1 = null;
            TcpClient client2 = null;

            server = new TcpListener(IPAddress.Any, 4042);
            server.Start();
            client1 = new TcpClient("localhost", 4042);
            client2 = new TcpClient("localhost", 4042);

            Socket serverSocket = server.AcceptSocket();

            Socket client1Socket = client1.Client;
            Socket client2Socket = client2.Client;

            StringSocket sendSocket = new StringSocket(serverSocket, new UTF8Encoding());
            StringSocket player1Socket = new StringSocket(client1Socket, new UTF8Encoding());
            StringSocket player2Socket = new StringSocket(client2Socket, new UTF8Encoding());

            BoggleServer.BoggleServer.Player player1 = new BoggleServer.BoggleServer.Player("ryan", player1Socket);
            BoggleServer.BoggleServer.Player player2 = new BoggleServer.BoggleServer.Player("ryan2", player2Socket);

            BoggleServer.BoggleServer.Match match = new BoggleServer.BoggleServer.Match(
                player1, player2, 60, new HashSet<string>(System.IO.File.ReadAllLines(@"..\..\..\Resources\Dictionary.txt")), "horstoaeaggdpple");

            match.ReceivedPlayer1Data("word horse", null, player1Socket);
            Assert.AreEqual(2, player1.Score);
            Assert.IsTrue(player1.UniqueLegalWords.Contains("HORSE"));
        }
コード例 #5
0
 public void Connect(string hostname, int port, string clientPassword)
 {
     // initial connection to the server
     if (clientSSocket == null)
     {
         password = clientPassword;
         try
         {
             TcpClient client = new TcpClient(hostname, port);
             clientSSocket = new StringSocket(client.Client, UTF8Encoding.Default);
             clientSSocket.BeginSend("PASSWORD" + "\\e" + password + "\n", (ex, p) => { }, null);
             clientSSocket.BeginReceive(LineReceived, null);
         }
         catch (SocketException e)
         {
             Console.WriteLine(e.Message);
         }
     }
     // not sure if this part is necessary?
     else
     {
         //clientSSocket.Close(); we don't want to close the socket unless the client is disconnecting
         TcpClient client = new TcpClient(hostname, port);
         clientSSocket = new StringSocket(client.Client, UTF8Encoding.Default);
         clientSSocket.BeginSend("PASSWORD"+ "\\e" + password + "\n", (ex, p) => { }, null);
         clientSSocket.BeginReceive(LineReceived, null);
     }
 }
コード例 #6
0
 /// <summary>
 /// Disconnect from any servers.
 /// </summary>
 public void Disconnect()
 {
     if (!ReferenceEquals(_stringSocket, null))
     {
         _stringSocket.Close();
         _stringSocket = null;
     }
 }
コード例 #7
0
        /// <summary>
        /// Connect to the server at the given hostname and port and with the given name.
        /// </summary>
        public void Connect(string hostname, int port)
        {
            // Connect or throw exception
            _client = new TcpClient(hostname, port);

            // Create a StringSocket for communicating with the server.
            _stringSocket = new StringSocket(_client.Client, UTF8Encoding.Default);           
        }
コード例 #8
0
ファイル: User.cs プロジェクト: unaveed/Spreadsheet
        public User(string _name, StringSocket _socket)
        {
            Name = _name;
            socket = _socket;
            Terminated = false;

            socket.BeginReceive(LineReceivedFromUser, socket);
        }
コード例 #9
0
 //make sure the client isn't already connected
 //then connect
 public void Connect(int port, string hostName)
 {
     if (ss == null)
     {
         TcpClient client = new TcpClient(hostName, port);
         ss = new StringSocket(client.Client, UTF8Encoding.Default);
         IsConnected = true;
     }
 }
コード例 #10
0
 //Disconnects the client, close the socket
 public void Disconnect()
 {
     if (ss != null)
     {
         ss.Close();
         IsConnected = false;
         ss = null;
     }
 }
コード例 #11
0
        /// <summary>
        /// Called when a Socket has been established as a result of a
        /// BeginAcceptSocket call.
        /// </summary>
        private void SocketAccepted(IAsyncResult ar)
        {
            Socket s = tcpListener.EndAcceptSocket(ar);
            var    internalPayload        = (Tuple <StringSocketCallback, object>)ar.AsyncState;
            StringSocketCallback callback = internalPayload.Item1;
            StringSocket         ss       = new StringSocket(s, encoding);
            object externalPayload        = internalPayload.Item2;

            callback(ss, externalPayload);
        }
コード例 #12
0
ファイル: ClientModel.cs プロジェクト: jiiehe/cs3500
 /// <summary>
 /// connects on the given port and ip
 /// </summary>
 /// <param name="port"></param>
 /// <param name="ip"></param>
 public void Connect(int port, string ip)
 {
     if (socket == null)
     {
         TcpClient client = new TcpClient(ip, port);
         socket = new StringSocket(client.Client, UTF8Encoding.Default);
         state = State.name;
         socket.BeginReceive(LineReceived, null);
     }
 }
コード例 #13
0
 /// <summary>
 /// Callback for trying to connect to Mission Control's PP. Will continually try to connect to reconnect until successful.
 /// </summary>
 /// <param name="ar"></param>
 private void MCConnect(IAsyncResult ar) {
     if (client.Connected) {
         PrimaryProgSocket = new StringSocket(client.Client, UTF8Encoding.Default);
         isConnectedToPrimProg = true;
     }
     else {
         isConnectedToPrimProg = false;
         client.BeginConnect(MCIP, MCPort, MCConnect, null);
     }
 }
コード例 #14
0
ファイル: Class1.cs プロジェクト: joesturz/Boggle
 /// <summary>
 /// Connect to the server at the given hostname and port and with the give name.
 /// </summary>
 public void Connect(string hostname, String name)
 {
     if (socket == null)
     {
         playerName = name;
         TcpClient client = new TcpClient(hostname, 2000);
         socket = new StringSocket(client.Client, UTF8Encoding.Default);
         socket.BeginSend("PLAY " + name + "\n", (e, p) => { }, null);
         socket.BeginReceive(LineReceived, null);
     }
 }
コード例 #15
0
ファイル: WebServer.cs プロジェクト: jimibue/cs3505
 /// <summary>
 /// This callback method is called when a connection has been received.
 /// </summary>
 private void ConnectionReceived(IAsyncResult ar)
 {
     Socket socket = server.EndAcceptSocket(ar);
     StringSocket ss = new StringSocket(socket, UTF8Encoding.Default);
     
     // Set the StringSocket to listen for a name from the client.
     ss.BeginReceive(GetReceived, ss);
     
     // Set the server to listen for another connection.
     server.BeginAcceptSocket(ConnectionReceived, null);
 }
コード例 #16
0
        public void SimpleTest()
        {
            // Declare these here so they are accessible in
            // the finally block
            TcpListener server = null;
            TcpClient   client = null;

            try
            {
                // Obtain a pair of sockets
                int port = 4002;
                server = new TcpListener(IPAddress.Any, port);
                server.Start();
                client = new TcpClient("localhost", port);
                Socket serverSocket = server.AcceptSocket();
                Socket clientSocket = client.Client;

                // Create a pair of StringSocket
                StringSocket sendSocket = new StringSocket(clientSocket, new UTF8Encoding());
                StringSocket rcvSocket  = new StringSocket(serverSocket, new UTF8Encoding());

                // Make sure that we receive the string "Hello"
                Asserter rcvAsserter = new Asserter();
                rcvSocket.BeginReceive((s, e, p) =>
                {
                    rcvAsserter.Expected = "Hello";
                    rcvAsserter.Actual   = s;
                    rcvAsserter.Set();
                },
                                       "");

                // Send a "Hello" and make sure the callback is called
                Asserter sendAsserter = new Asserter();
                sendSocket.BeginSend(
                    "Hello\n",
                    (e, p) =>
                {
                    sendAsserter.Expected = "Payload";
                    sendAsserter.Actual   = p;
                    sendAsserter.Set();
                },
                    "Payload");

                // Perform the assertions in the main testing thread
                sendAsserter.WaitAreEqual(2000);
                rcvAsserter.WaitAreEqual(2000);
            }
            finally
            {
                // Close everything down
                server.Stop();
                client.Close();
            }
        }
コード例 #17
0
ファイル: BoggleClientModel.cs プロジェクト: jimibue/cs3505
        /// <summary>
        /// Connect to the server at the given hostname and port, with the given name.
        /// </summary>
        public void Connect(String hostname, int port, String name)
        {
            if (socket == null)
            {
                TcpClient client = new TcpClient(hostname, port);
                socket = new StringSocket(client.Client, UTF8Encoding.Default);

                this.name = name;
                this.hostname = hostname;

                socket.BeginSend("PLAY " + name + "\n", (e, p) => { }, null);
                socket.BeginReceive(LineReceived, null);
            }
        }
コード例 #18
0
ファイル: BoggleClientModel.cs プロジェクト: jimibue/cs3505
        /// <summary>
        /// Connect to the server at the given hostname and port and with the give name.
        /// </summary>
        public void Connect(string hostname, int port, String name)
        {
            if (socket == null||!validName )
            {
                if (name.StartsWith("PLAY ") && name.Substring(5).Trim().Length > 0)
                    validName = true;
                
                TcpClient client = new TcpClient(hostname, port);
                socket = new StringSocket(client.Client, UTF8Encoding.Default);

                socket.BeginSend(name + "\n", (e, p) => { }, null);
                socket.BeginReceive(LineReceived, null);
            }
        }
コード例 #19
0
 /// <summary>
 /// Connect to the server at the given hostname and port and with the give name.
 /// </summary>
 public void Connect(string hostname, int port)
 {
     Console.WriteLine("ChatClientModel Connect called");
     if (!connected) {
         if (socket == null)
         {
             TcpClient client = new TcpClient(hostname, port);
             socket = new StringSocket(client.Client, UTF8Encoding.Default);
             socket.BeginReceive(LineReceived, null);
         }
     }
     else {
         throw new Exception("Already connected!");
     }
 }
コード例 #20
0
ファイル: Program.cs プロジェクト: jiiehe/cs3500
        static void Main(string[] args)
        {
            //new server
            TcpListener server = new TcpListener(IPAddress.Any, 4010);

            server.Start();
            //blocks until user connects
            Socket serverSocket = server.AcceptSocket();
            Console.WriteLine("hey");

            // Wrap the two ends of the connection into StringSockets
            StringSocket sendSocket = new StringSocket(serverSocket, new UTF8Encoding());
            sendSocket.BeginSend("hi", (e, o) => { }, null);
            Console.ReadLine();
        }
コード例 #21
0
 /// <summary>
 /// Connect to the server at the given hostname and port and with the give name.
 /// </summary>
 public void Connect(string IPAddress, String name)
 {
     if (socket == null)
     {
         try
         {
             TcpClient client = new TcpClient(IPAddress, 2000);
             socket = new StringSocket(client.Client, UTF8Encoding.Default);
             socket.BeginSend("PLAY " + name + "\n", (e, p) => { }, null);
             socket.BeginReceive(LineReceived, null);
         }
         catch (Exception e)
         {
             //no such host event
             noSuchHostEvent(e.Message);
         }
     }
 }
コード例 #22
0
ファイル: Class1.cs プロジェクト: keivnlee/Spreadsheet
 /// <summary>
 /// Takes a string representing the IP Address of the server, an int with the port number and the players name.
 /// It then connects to the server and sends the play message with the players name.
 /// </summary>
 public void Connect(String password)
 {
     if (socket == null || !socket.Connected())
     {
         // Tries to connect to the server and then send the play message
         try
         {
             TcpClient client = new TcpClient(IP, port);
             socket = new StringSocket(client.Client, UTF8Encoding.Default);
             socket.BeginSend(password, (e, p) => { }, null);
             socket.BeginReceive(LineReceived, null);
         }
         // If it is unable to connect it catches the exception and throws it on
         catch (SocketException e)
         {
             throw e;
         }
     }
 }
コード例 #23
0
ファイル: UnitTest1.cs プロジェクト: ryoia/BoggleGames
        public void runGame()
        {
            server = new BoggleServer.BoggleServer(2000, 10, "..\\..\\..\\dictionary", "AAAABBBBCCCCDDDD");
            player1 = new TcpClient("localhost", 2000);
            player2 = new TcpClient("localhost", 2000);
            Socket p1socket = player1.Client;
            Socket p2socket = player2.Client;
            p1 = new StringSocket(p1socket, new UTF8Encoding());
            p2 = new StringSocket(p2socket, new UTF8Encoding());
            p1.BeginSend("PLAY player1\n", (e, o) => { }, null);
            p2.BeginSend("PLAY player2\n", (e, o) => { }, null);
            mre = new ManualResetEvent(false);
            receivedWords = new List<string>();
            for (int i = 0; i < 20; i++)
            {
                p1.BeginReceive(callback, p1);
            }
            mre.WaitOne(1000);

            Assert.IsTrue(receivedWords.Contains("START AAAABBBBCCCCDDDD 10 PLAYER2"));
        }
コード例 #24
0
ファイル: BoggleTests.cs プロジェクト: jiiehe/cs3500
        public void TestDisconnect()
        {
            string[] toArgs = new string[3];
            toArgs[0] = "5";
            toArgs[1] = "..\\..\\..\\dictionary.txt";
            toArgs[2] = "TAPRVILRGTOAEUEQ";
            ThreadPool.QueueUserWorkItem((e) => { BoggleServer.Main(toArgs); });

            List<StringSocket> clients = new List<StringSocket>();

            int CLIENT_COUNT = 2;//not a constant, I know.
            for (int i = 0; i < CLIENT_COUNT; i++)
            {
                TcpClient tempClient = new TcpClient("localhost", 2000);
                Socket tempclientSocket = tempClient.Client;
                StringSocket SS = new StringSocket(tempclientSocket, new UTF8Encoding());
                clients.Add(SS);
            }

            string clientString0 = "";
            string clientString1 = "";
            clients[0].BeginSend("PLAY Dylan\n", (e, p) => { }, 1);
            clients[1].BeginSend("PLAY ToClose\n", (e, p) => { clients[1].BeginReceive((s, ee, pp) => { clientString1 = s; }, 1); }, 1);

            Thread.Sleep(500);

            clientString0 = "";

            string clientString0next = "";

            clients[1].Close();

            clients[0].BeginReceive((s, ee, pp) => { clientString0 = s; }, 1);
            clientString0next = catchMessage(clientString0, 0, "TERMINATED", clients[0]);

            Assert.AreEqual("TERMINATED", clientString0next);
        }
コード例 #25
0
ファイル: BS.cs プロジェクト: ryoia/BoggleGames
 // WEB SERVER
 /// <summary>
 /// Callback for Web Server Listener
 /// -Creates a socket between client and server.
 /// -Begins receiving data from the client (URL information)
 /// -Recalls WebServerListener to listen for more page views.
 /// </summary>
 private void WebServerConnectionRequested(IAsyncResult result)
 {
     StringSocket ss = new StringSocket(webServerListener.EndAcceptSocket(result), new UTF8Encoding());
     ss.BeginReceive(WebRequestServerStart, ss);
     webServerListener.BeginAcceptSocket(WebServerConnectionRequested, null);
 }
コード例 #26
0
 public BoggleClientModel()
 {
     ss = null;
 }
コード例 #27
0
 /// <summary>
 /// Returns true once a games has two players, false otherwise
 /// </summary>
 /// <param name="playerName"></param>
 /// <param name="socket"></param>
 /// <returns></returns>
 public bool addPlayer(string playerName, StringSocket socket, int game)
 {
     if (player1Name == null)
     {
         player1Name = playerName;
         player1 = socket;
         player1.Player = 1;
         player1.Game = game;
         return false;
     }
     else
     {
         player2Name = playerName;
         player2 = socket;
         player2.Player = 2;
         player2.Game = game;
         return true;
     }
 }
コード例 #28
0
 public SpreadsheetClientModel()
 {
     clientSSocket = null;
 }
コード例 #29
0
ファイル: StringSocketTest.cs プロジェクト: jimibue/cs3505
            public void run(int port)
            {
                // Create and start a server and client.
                TcpListener server = null;
                TcpClient client = null;

                try
                {
                    server = new TcpListener(IPAddress.Any, port);
                    server.Start();
                    client = new TcpClient("localhost", port);

                    // Obtain the sockets from the two ends of the connection.  We are using the blocking AcceptSocket()
                    // method here, which is OK for a test case.
                    Socket serverSocket = server.AcceptSocket();
                    Socket clientSocket = client.Client;

                    // Wrap the two ends of the connection into StringSockets
                    StringSocket sendSocket = new StringSocket(serverSocket, new UTF8Encoding());
                    StringSocket receiveSocket = new StringSocket(clientSocket, new UTF8Encoding());

                    // This will coordinate communication between the threads of the test cases
                    mre1 = new ManualResetEvent(false);
                    mre2 = new ManualResetEvent(false);

                    // Make two receive requests
                    receiveSocket.BeginReceive(CompletedReceive1, 1);
                    receiveSocket.BeginReceive(CompletedReceive2, 2);

                    // Now send the data.  Hope those receive requests didn't block!
                    String msg = "Hello world\nThis is a test\n";
                    foreach (char c in msg)
                    {
                        sendSocket.BeginSend(c.ToString(), (e, o) => { }, null);
                    }

                    // Make sure the lines were received properly.
                    Assert.AreEqual(true, mre1.WaitOne(timeout), "Timed out waiting 1");
                    Assert.AreEqual("Hello world", s1);
                    Assert.AreEqual(1, p1);

                    Assert.AreEqual(true, mre2.WaitOne(timeout), "Timed out waiting 2");
                    Assert.AreEqual("This is a test", s2);
                    Assert.AreEqual(2, p2);
                }
                finally
                {
                    server.Stop();
                    client.Close();
                }
            }
コード例 #30
0
        /// <summary>
        /// Creates a client communicating with the remote host via the given port
        /// using the provided encoding over a StringSocket.
        /// </summary>
        public StringSocketClient(string host, int port, Encoding encoding)
        {
            Socket s = new TcpClient(host, port).Client;

            Client = new StringSocket(s, encoding);
        }
コード例 #31
0
ファイル: BS.cs プロジェクト: ryoia/BoggleGames
        // HELPER METHODS
        /// <summary>
        /// WebPage containing record of each player.
        /// </summary>
        private void PlayerRecordsWebPage(StringSocket ss)
        {
            using (MySqlConnection connect = new MySqlConnection(connectionString))
            {
                // Open MySqlConnection to Database
                connect.Open();

                MySqlCommand command = connect.CreateCommand();
                MySqlDataReader reader;

                // Begin to send HTML Web Page
                ss.BeginSend("HTTP/1.1 200 OK\r\n", (ee, pp) => { }, null);
                ss.BeginSend("Connection: close\r\n", (ee, pp) => { }, null);
                ss.BeginSend("Content-Type: text/html; charset=UTF-8\r\n", (ee, pp) => { }, null);
                ss.BeginSend("\r\n", (ee, pp) => { }, null);

                // Store HTML Page
                List<String> webPage = new List<String>();
                webPage.Add("<html>");
                webPage.Add("<title>Boggle Records</title>");
                webPage.Add("<body>");
                webPage.Add("<h1>Boggle Players Records</h1>");
                webPage.Add("<table border=\"1\">");
                webPage.Add("<tr><td>Player</td><td>Games Won</td><td>Games Lost</td><td>Games Tied</td></tr>");

                // Sorted Dictionary to Store Wicked-Awesome Query
                SortedDictionary<String, Int32[]> playerWinsLossesTies = new SortedDictionary<String, Int32[]>();

                // Query for Tied (Bool), PlayerAName, PlayerBName, WinnerName, LoserName
                command.CommandText = @"
                                    SELECT Tied,
                                        PlayerAName.PlayerName AS 'Tie A Name',
                                        PlayerBName.PlayerName AS 'Tie B Name' ,
                                        WinName.PlayerName AS 'Winner',
                                        LoseName.PlayerName AS 'Loser'
                                    FROM GameInfo AS Game
                                         LEFT JOIN Players AS PlayerAName
                                                   ON Game.PlayerAID=PlayerAName.PlayerID
                                         LEFT JOIN Players AS PlayerBName
                                                   ON Game.PlayerBID=PlayerBName.PlayerID
                                         LEFT JOIN Players AS WinName
                                                   ON Game.WinnerName=WinName.PlayerID
                                         LEFT JOIN Players AS LoseName
                                                   ON Game.LoserName=LoseName.PlayerID";
                command.Parameters.Clear();

                using (reader = command.ExecuteReader())
                {
                    // For every result from the Query
                    while (reader.Read())
                    {
                        // If tied is false, then we know there must be a winner
                        if (reader.GetInt32(0) == 0)
                        {
                            String keyNameWinner;
                            String keyNameLoser;
                            try
                            {
                                keyNameWinner = reader.GetString(3);
                                keyNameLoser = reader.GetString(4);
                            }
                            catch
                            {
                                continue;
                            }

                            // Add one point to Winner Score
                            if (playerWinsLossesTies.ContainsKey(keyNameWinner))
                            {
                                playerWinsLossesTies[keyNameWinner][0] += 1;
                            }
                            else
                            {
                                playerWinsLossesTies.Add(keyNameWinner, new int[]{1,0,0});
                            }

                            // Add one point to Loser Score
                            if (playerWinsLossesTies.ContainsKey(keyNameLoser))
                            {
                                playerWinsLossesTies[keyNameLoser][1] += 1;
                            }
                            else
                            {
                                playerWinsLossesTies.Add(keyNameLoser, new int[] { 0, 1, 0 });
                            }
                        }
                        // Both Player A and Player B must be Tied
                        else if (reader.GetInt32(0) == 1)
                        {
                            String keyTiedPlayerA;
                            String keyTiedPlayerB;

                            try
                            {
                                keyTiedPlayerA = reader.GetString(1);
                                keyTiedPlayerB = reader.GetString(2);
                            }
                            catch
                            {
                                continue;
                            }

                            // Add point to both players tied scores
                            if (playerWinsLossesTies.ContainsKey(keyTiedPlayerA))
                            {
                                playerWinsLossesTies[keyTiedPlayerA][2] += 1;
                            }
                            else
                            {
                                playerWinsLossesTies.Add(keyTiedPlayerA, new int[] { 0, 0, 1 });
                            }

                            if (playerWinsLossesTies.ContainsKey(keyTiedPlayerB))
                            {
                                playerWinsLossesTies[keyTiedPlayerB][2] += 1;
                            }
                            else
                            {
                                playerWinsLossesTies.Add(keyTiedPlayerB, new int[] { 0, 0, 1 });
                            }
                        }

                    }
                }

                foreach (KeyValuePair<String, Int32[]> row in playerWinsLossesTies)
                {
                    webPage.Add("<tr><td><a href=\"/games?player=" + row.Key + "\">" + row.Key + "</a></td><td>" + row.Value[0] + "</td><td>" + row.Value[1] + "</td><td>" + row.Value[2] + "</td></tr>");
                }

                webPage.Add("</table>");

                webPage.Add("</body>");
                webPage.Add("</html>\n");

                StringBuilder webPageAsString = new StringBuilder();
                foreach (String line in webPage)
                {
                    webPageAsString.Append(line);
                }

                // Send webpage to user.
                ss.BeginSend(webPageAsString.ToString(), (ee, pp) => { CloseSocketCallback(ss); }, null);
            }
        }
コード例 #32
0
ファイル: BS.cs プロジェクト: ryoia/BoggleGames
        /// <summary>
        /// WebPage containing an individual player's Game History
        /// </summary>
        private void PlayerGameHistoryWebPage(StringSocket ss, string playerName)
        {
            using (MySqlConnection connect = new MySqlConnection(connectionString))
            {
                // Open MySqlConnection to Database
                connect.Open();

                using (MySqlCommand command = connect.CreateCommand())
                {
                    // Query for Player ID and Count
                    command.CommandText = "select PlayerID, count(*) from Players where PlayerName = @playerName;";
                    command.Parameters.Clear();
                    command.Parameters.AddWithValue("@playerName", playerName);
                    command.Prepare();

                    int numRowsWithPlayerID = 0;
                    int playerID = 0;

                    MySqlDataReader reader;

                    // Read query results and store Player ID
                    using (reader = command.ExecuteReader())
                    {
                        if (reader.Read())
                        {
                            numRowsWithPlayerID = reader.GetInt32(1);

                            try
                            {
                                playerID = reader.GetInt32(0);
                            }
                            catch
                            {
                            }
                        }
                    }

                    // If Query for PlayerID yields no rows, send to ErrorWebPage
                    if (numRowsWithPlayerID == 0)
                    {
                        ErrorWebPage(ss);
                    }
                    // Else build WebPage
                    else
                    {
                        // Begin to send HTML Web Page
                        ss.BeginSend("HTTP/1.1 200 OK\r\n", (ee, pp) => { }, null);
                        ss.BeginSend("Connection: close\r\n", (ee, pp) => { }, null);
                        ss.BeginSend("Content-Type: text/html; charset=UTF-8\r\n", (ee, pp) => { }, null);
                        ss.BeginSend("\r\n", (ee, pp) => { }, null);

                        // WebPage as List
                        List<String> webPage = new List<String>();

                        webPage.Add("<html>");
                        webPage.Add("<title>"+ playerName + ((playerName[playerName.Length-1]==('s'))?"\'":"\'s") + " Game History</title>");
                        webPage.Add("<body>");
                        webPage.Add("<h1>"+ playerName + ((playerName[playerName.Length-1]==('s'))?"\'":"\'s") + " Game History</h1>");
                        webPage.Add("<table border=\"1\">");

                        // Table column headers
                        webPage.Add("<tr><td>Game ID</td><td>Date</td><td>Time</td><td>Opponent Name</td><td>Player Score</td><td>Opponent Score</td></tr>");

                        string opponentName = "";
                        bool isPlayerA = false;
                        //get the game IDs associate to the playerID
                        List<int> gameIDs = new List<int>();
                        command.CommandText = "select GameID from GameInfo where (PlayerAID = @playerID or PlayerBID = @playerID);";
                        command.Parameters.Clear();
                        command.Parameters.AddWithValue("@playerID", playerID);
                        command.Prepare();
                        using (reader = command.ExecuteReader())
                        {
                            while (reader.Read())
                            {
                                gameIDs.Add(reader.GetInt32(0));
                            }
                        }

                        // Get EndDate Time, PlayerA's Score, and Player B's Score For Each game

                        foreach (int gameID in gameIDs)
                        {
                            // Query for EndDate Time, PlayerA's Score, and Player B's Score
                            opponentName = CheckPlayerAOrB(command, ref reader, gameID, playerID, ref isPlayerA);
                            command.CommandText = "select EndDateTime, ScoreA, ScoreB from GameInfo where GameID = @gameID;";
                            command.Parameters.Clear();
                            command.Parameters.AddWithValue("@gameID", gameID);
                            command.Prepare();

                            string endDateTime = "";
                            int playerAscore = 0;
                            int playerBscore = 0;
                            using (reader = command.ExecuteReader())
                            {
                                if (reader.Read())
                                {
                                    endDateTime = reader.GetString(0);
                                    playerAscore = reader.GetInt32(1);
                                    playerBscore = reader.GetInt32(2);
                                }
                            }

                            // Regex for Date and Time
                            Regex dateRegex = new Regex(@"\d+/\d+/\d+");
                            Regex timeRegex = new Regex(@"\d+:\d+:\d+ [AP]M");

                            // Depending on if player is A or B in game, add row to table with correct formatting.
                            if (isPlayerA)
                                webPage.Add("<tr><td><a href=\"/game?id=" + gameID + "\">" + gameID + "</a></td><td>" + dateRegex.Match(endDateTime).ToString() + "</td><td>" + timeRegex.Match(endDateTime).ToString() + "</td><td><a href=\"/games?player=" + opponentName + "\">" + opponentName + "</a></td><td>" + playerAscore + "</td><td>" + playerBscore + "</td></tr>");
                            else
                                webPage.Add("<tr><td><a href=\"/game?id=" + gameID + "\">" + gameID + "</a></td><td>" + dateRegex.Match(endDateTime).ToString() + "</td><td>" + timeRegex.Match(endDateTime).ToString() + "</td><td><a href=\"/games?player=" + opponentName + "\">" + opponentName + "</a></td><td>" + playerBscore + "</td><td>" + playerAscore + "</td></tr>");
                        }

                        webPage.Add("</table>");
                        webPage.Add("<a href=\"/players\">Boggle Records</a>");
                        webPage.Add("</body>");
                        webPage.Add("</html>\n");

                        StringBuilder webPageAsString = new StringBuilder();

                        foreach (String line in webPage)
                        {
                            webPageAsString.Append(line);
                        }

                        // Send WebPage to Client
                        ss.BeginSend(webPageAsString.ToString(), (ee, pp) => { CloseSocketCallback(ss); }, null);
                    }
                }
            }
        }
コード例 #33
0
ファイル: BS.cs プロジェクト: ryoia/BoggleGames
        /// <summary>
        /// WebPage containing the summary of an individual Game
        /// </summary>
        private void GameSummaryWebPage(StringSocket ss, int gameID)
        {
            using (MySqlConnection connect = new MySqlConnection(connectionString))
            {
                using (MySqlCommand command = connect.CreateCommand())
                {
                    // Open MySqlConnection to Database
                    connect.Open();

                    // Query for GameID and Count
                    command.CommandText = "select count(*) from GameInfo where GameID = @gameID";
                    command.Parameters.Clear();
                    command.Parameters.AddWithValue("@gameID", gameID);
                    command.Prepare();

                    MySqlDataReader reader;

                    int numRowsWithGameID = 0;
                    using (reader = command.ExecuteReader())
                    {
                        if (reader.Read())
                        {
                            numRowsWithGameID = reader.GetInt32(0);
                        }
                    }

                    // If Query for GameID yields no rows, send to Error Web Page
                    if (numRowsWithGameID == 0)
                    {
                        ErrorWebPage(ss);
                    }
                    else
                    {
                        // Begin to send HTML Web Page
                        ss.BeginSend("HTTP/1.1 200 OK\r\n", (ee, pp) => { }, null);
                        ss.BeginSend("Connection: close\r\n", (ee, pp) => { }, null);
                        ss.BeginSend("Content-Type: text/html; charset=UTF-8\r\n", (ee, pp) => { }, null);
                        ss.BeginSend("\r\n", (ee, pp) => { }, null);

                        // Store Web Page
                        List<String> webPage = new List<String>();

                        webPage.Add("<html>");
                        webPage.Add("<title>Boggle Game "+ gameID +" - Summary</title>");
                        webPage.Add("<body>");
                        webPage.Add("<h1>Game " + gameID + " Summary</h1>");

                        // Query for PlayerAID, Score A, SummaryA, PlayerBID, Score B, SummaryB, End Date Time, Time Limit, and Board
                        command.CommandText = "select PlayerAID, ScoreA, SummaryA, PlayerBID, ScoreB, SummaryB, EndDateTime, TimeLimit, Board from GameInfo where GameID = @gameID;";
                        command.Parameters.Clear();
                        command.Parameters.AddWithValue("@gameID", gameID);
                        command.Prepare();

                        int playerAID = 0;
                        int playerBID = 0;
                        int playerAScore = 0;
                        int playerBScore = 0;
                        string playerASummary = "";
                        string playerBSummary = "";
                        string endDateTime = "";
                        int timeLimit = 0;
                        string board = "";

                        using (reader = command.ExecuteReader())
                        {
                            if (reader.Read())
                            {
                                playerAID = reader.GetInt32(0);
                                playerAScore = reader.GetInt32(1);
                                playerASummary = reader.GetString(2);
                                playerBID = reader.GetInt32(3);
                                playerBScore = reader.GetInt32(4);
                                playerBSummary = reader.GetString(5);
                                endDateTime = reader.GetString(6);
                                timeLimit = reader.GetInt32(7);
                                board = reader.GetString(8);
                            }
                        }

                        // Query for PlayerA and PlayerB Names
                        string playerAName = "";
                        string playerBName = "";

                        playerAName = GetNameFromID(ref reader, playerAID, command);
                        playerBName = GetNameFromID(ref reader, playerBID, command);

                        // Create Table for PlayerA and PlayerB Stats
                        webPage.Add("<h3>Time Limit: " + timeLimit + "</br>Date & Time: " + endDateTime + "</br></h3>");
                        webPage.Add("<table border = \"1\">");
                        webPage.Add("<tr><td>Player A's Name</td><td><a href=\"/games?player=" + playerAName + "\">" + playerAName + "</a></td></tr>");
                        webPage.Add("<tr><td>Player A's Score</td><td>" + playerAScore + "</td></tr>");
                        webPage.Add("<tr><td>Player A's Summary</td><td>" + playerASummary + "</td></tr>");
                        webPage.Add("</table>");

                        webPage.Add("<table border = \"1\">");
                        webPage.Add("<tr><td>Player B's Name</td><td><a href=\"/games?player=" + playerBName + "\">" + playerBName + "</a></td></tr>");
                        webPage.Add("<tr><td>Player B's Score</td><td>" + playerBScore + "</td></tr>");
                        webPage.Add("<tr><td>Player B's Summary</td><td>" + playerBSummary + "</td></tr>");
                        webPage.Add("</table>");

                        webPage.Add("<p>");

                        // Create Table of Game Board
                        webPage.Add("<table border = \"1\" bgcolor=\"#FF8000\" cellspacing=\"5\" cellpadding=\"4\">");
                        webPage.Add("</tr> <td bgcolor=\"maroon\"><img src = \"https://dl.dropboxusercontent.com/u/87615358/Images/" + board[0].ToString() + ".png\"></td> <td bgcolor=\"maroon\"><img src = \"https://dl.dropboxusercontent.com/u/87615358/Images/" + board[1].ToString() + ".png\"></td> <td bgcolor=\"maroon\"><img src = \"https://dl.dropboxusercontent.com/u/87615358/Images/" + board[2].ToString() + ".png\"></td> <td bgcolor=\"maroon\"><img src = \"https://dl.dropboxusercontent.com/u/87615358/Images/" + board[3].ToString() + ".png\"></td> </tr>");
                        webPage.Add("</tr> <td bgcolor=\"maroon\"><img src = \"https://dl.dropboxusercontent.com/u/87615358/Images/" + board[4].ToString() + ".png\"></td> <td bgcolor=\"maroon\"><img src = \"https://dl.dropboxusercontent.com/u/87615358/Images/" + board[5].ToString() + ".png\"></td> <td bgcolor=\"maroon\"><img src = \"https://dl.dropboxusercontent.com/u/87615358/Images/" + board[6].ToString() + ".png\"></td> <td bgcolor=\"maroon\"><img src = \"https://dl.dropboxusercontent.com/u/87615358/Images/" + board[7].ToString() + ".png\"></td> </tr>");
                        webPage.Add("</tr> <td bgcolor=\"maroon\"><img src = \"https://dl.dropboxusercontent.com/u/87615358/Images/" + board[8].ToString() + ".png\"></td> <td bgcolor=\"maroon\"><img src = \"https://dl.dropboxusercontent.com/u/87615358/Images/" + board[9].ToString() + ".png\"></td> <td bgcolor=\"maroon\"><img src = \"https://dl.dropboxusercontent.com/u/87615358/Images/" + board[10].ToString() + ".png\"></td> <td bgcolor=\"maroon\"><img src = \"https://dl.dropboxusercontent.com/u/87615358/Images/" + board[11].ToString() + ".png\"></td> </tr>");
                        webPage.Add("</tr> <td bgcolor=\"maroon\"><img src = \"https://dl.dropboxusercontent.com/u/87615358/Images/" + board[12].ToString() + ".png\"></td> <td bgcolor=\"maroon\"><img src = \"https://dl.dropboxusercontent.com/u/87615358/Images/" + board[13].ToString() + ".png\"></td> <td bgcolor=\"maroon\"><img src = \"https://dl.dropboxusercontent.com/u/87615358/Images/" + board[14].ToString() + ".png\"></td> <td bgcolor=\"maroon\"><img src = \"https://dl.dropboxusercontent.com/u/87615358/Images/" + board[15].ToString() + ".png\"></td> </tr>");
                        webPage.Add("</table>");

                        webPage.Add("<a href=\"/players\">Boggle Records</a>");

                        webPage.Add("</body>");
                        webPage.Add("</html>\n");

                        StringBuilder webPageAsString = new StringBuilder();

                        foreach (String line in webPage)
                        {
                            webPageAsString.Append(line);
                        }

                        // Send rest of Web Page
                        ss.BeginSend(webPageAsString.ToString(), (ee, pp) => { CloseSocketCallback(ss); }, null);
                    }
                }
            }
        }