Exemplo n.º 1
0
 /// <summary>
 /// Send a line of text to the server.
 /// </summary>
 /// <param name="line"></param>
 public void SendMessage(String line)
 {
     if (socket != null)
     {
         socket.BeginSend(line + "\n", (e, p) => { }, null);
     }
 }
Exemplo n.º 2
0
            public void run()
            {
                BoggleServer.BoggleServer server = null;
                TcpClient client = null;

                try
                {
                    string[] args = { "200", "../../../Resources/dictionary.txt" };
                    server = new BoggleServer.BoggleServer(args);

                    // create player one connection
                    client = new TcpClient("localhost", 2000);
                    Socket       clientSocket = client.Client;
                    StringSocket player       = new StringSocket(clientSocket, new UTF8Encoding());

                    mre = new ManualResetEvent(false);

                    // have player one join the boggle game
                    player.BeginSend("", (o, e) => { mre.Set(); }, null);
                    player.BeginSend("foo bar", (o, e) => { mre.Set(); }, null);

                    // waits for one second, expecting the callback to trigger the mre signal
                    Assert.IsTrue(mre.WaitOne(1000));
                }
                finally
                {
                    server.Stop();
                    client.Close();
                }
            }
Exemplo n.º 3
0
        public void CreateNewGameWithInvalidPlay()
        {
            BoggleServer.Server server = new BoggleServer.Server(2000, new string[] { "200", "Dictionary.txt" });

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

            StringSocket client1 = Client.CreateClient(2000);

            //Wrong Play comment
            client1.BeginSend("PALY ENTEREDWRONG\n", (e, o) => { }, null);

            StringSocket client2 = Client.CreateClient(2000);

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

            //Now enter in the command correctly so that the game can still be started
            client1.BeginSend("PLAY ENTEREDCORRECTLY\n", (e, o) => { }, null);

            client1.BeginReceive(ReceiveClient1, "Client1");
            client2.BeginReceive(ReceiveClient2, "Client2");

            // Make sure client 1 gets ignore message due to bad command
            Assert.AreEqual(true, mre1.WaitOne(timeout), "Timed out waiting 1");
            Assert.AreEqual("IGNORING", s1.Substring(0, 8));
            Assert.AreEqual("Client1", p1);

            // Make sure client 2 gets start message signifying that client 1's resend worked this time
            Assert.AreEqual(true, mre2.WaitOne(timeout), "Timed out waiting 2");
            Assert.AreEqual("START", s2.Substring(0, 5));
            Assert.AreEqual("Client2", p2);

            server.CloseServer();
        }
Exemplo n.º 4
0
        private void ContentReceived(string s, Exception e, object payload)
        {
            if (s != null)
            {
                Person p = JsonConvert.DeserializeObject <Person>(s);
                Console.WriteLine(p.Name + " " + p.Eyes);

                // Call service method

                string result =
                    JsonConvert.SerializeObject(
                        new Person {
                    Name = "June", Eyes = "Blue"
                },
                        new JsonSerializerSettings {
                    NullValueHandling = NullValueHandling.Ignore
                });

                ss.BeginSend("HTTP/1.1 200 OK\n", Ignore, null);
                ss.BeginSend("Content-Type: application/json\n", Ignore, null);
                ss.BeginSend("Content-Length: " + result.Length + "\n", Ignore, null);
                ss.BeginSend("\r\n", Ignore, null);
                ss.BeginSend(result, (ex, py) => { ss.Shutdown(); }, null);
            }
        }
Exemplo n.º 5
0
        /// <summary>
        /// Recieves message from client.
        /// </summary>
        /// <param name="message">Protocol string</param>
        /// <param name="e">Exception thrown by String Socket (if any)</param>
        /// <param name="payload">String Socket object</param>
        private void messageReceived(string message, Exception e, Object payload)
        {
            if (message == null)
            {
                return;
            }
            if (e != null)
            {
                throw e;
            }
            StringSocket ss = (StringSocket)payload;

            Console.WriteLine("Received Message: " + message);
            if (message.ToUpper().StartsWith("RECOMMEND"))
            {
                message = message.Substring(10);
                List <String> recs       = getRecommendation(message);
                string        recsString = "RECOMMEND " + string.Join(@"%%%", recs) + "\n";
                Console.WriteLine("Sending Message: " + recsString);
                ss.BeginSend(recsString, sendCallback, null);
            }
            else if (message.ToUpper().StartsWith("AUTHOR"))
            {
                message = message.Substring(7);
                string author = getAuthor(message);
                author = "AUTHOR " + author + "\n";
                Console.WriteLine("Sending Message: " + author);
                ss.BeginSend(author, sendCallback, null);
            }
            ss.BeginReceive(messageReceived, ss);
        }
Exemplo n.º 6
0
            public void run(int port)
            {
                int         LIMIT = 1000;
                int         count = LIMIT;
                Socket      s1, s2;
                TcpListener server;

                OpenSockets(port, out server, out s1, out s2);
                List <int> lines = new List <int>();

                for (int i = 0; i < LIMIT; i++)
                {
                    lines.Add(-1);
                }
                StringSocket sender   = null;
                SS           receiver = null;

                try
                {
                    sender   = new StringSocket(s1, new UTF8Encoding());
                    receiver = new SS(s2, new UTF8Encoding());
                    for (int i = 0; i < LIMIT / 4; i++)
                    {
                        int j = i;
                        receiver.BeginReceive((s, e, p) => { lock (lines) { lines[j] = Int32.Parse(s); } Interlocked.Decrement(ref count); }, null);
                    }
                    for (int i = 0; i < LIMIT / 2; i++)
                    {
                        sender.BeginSend(i.ToString() + "\n", (e, p) => { }, null);
                    }
                    for (int i = LIMIT / 4; i < 3 * LIMIT / 4; i++)
                    {
                        int j = i;
                        receiver.BeginReceive((s, e, p) => { lock (lines) { lines[j] = Int32.Parse(s); } Interlocked.Decrement(ref count); }, null);
                    }
                    for (int i = LIMIT / 2; i < LIMIT; i++)
                    {
                        sender.BeginSend(i.ToString() + "\n", (e, p) => { }, null);
                    }
                    for (int i = 3 * LIMIT / 4; i < LIMIT; i++)
                    {
                        int j = i;
                        receiver.BeginReceive((s, e, p) => { lock (lines) { lines[j] = Int32.Parse(s); Interlocked.Decrement(ref count); } }, null);
                    }

                    if (!SpinWait.SpinUntil(() => count == 0, 5000))
                    {
                        Assert.Fail();
                    }
                    for (int i = 0; i < LIMIT; i++)
                    {
                        Assert.AreEqual(i, lines[i]);
                    }
                }
                finally
                {
                    CloseSockets(server, sender, receiver);
                }
            }
Exemplo n.º 7
0
        public void TestSameWord()
        {
            BoggleServer.Server server = new BoggleServer.Server(2000, new string[] { "20", "Dictionary.txt", "potscatscarsteps" });

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

            StringSocket client1 = Client.CreateClient(2000);

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

            StringSocket client2 = Client.CreateClient(2000);

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

            client1.BeginReceive(ReceiveClient1, "Client1");

            client2.BeginReceive(ReceiveClient2, "Client2");

            client1.BeginSend("word Pots\n", (e, o) => { }, "Client1");
            client2.BeginSend("word Pots\n", (e, o) => { }, "Client2");

            client1.BeginReceive(ReceiveScore1, "Client1");

            client2.BeginReceive(ReceiveScore2, "Client2");


            client1.BeginReceive(ReceiveScore1, "Client1");

            client2.BeginReceive(ReceiveScore2, "Client2");

            System.Threading.Thread.Sleep(1000);



            // Make sure client 1 gets start message
            Assert.AreEqual(true, mre1.WaitOne(timeout), "Timed out waiting 1");
            Assert.AreEqual("START", s1.Substring(0, 5));
            Assert.AreEqual("Client1", p1);

            // Make sure client 2 gets start message
            Assert.AreEqual(true, mre2.WaitOne(timeout), "Timed out waiting 2");
            Assert.AreEqual("START", s2.Substring(0, 5));
            Assert.AreEqual("Client2", p2);

            // Make sure Client 1 gets the score message
            Assert.AreEqual(true, mre3.WaitOne(timeout), "Timed out waiting 3");
            Assert.AreEqual("SCORE 0 0", s3, "Score passed Incorrectly");

            // Makes sure Client 2 gets the score message
            Assert.AreEqual(true, mre4.WaitOne(timeout), "Timed out waiting 4");
            Assert.AreEqual("SCORE 0 0", s4, "Score passed Incorrectly");

            // Closes the server
            server.CloseServer();
        }
Exemplo n.º 8
0
        /// <summary>
        /// Event handler for Go button click
        /// </summary>
        private void goButton_Click(object sender, EventArgs e)
        {
            string title = queryBox.Text;

            if (title == "")
            {
                MessageBox.Show("You must enter a title to get a recommendation.");
            }
            ss.BeginSend("RECOMMEND " + title, sendCallback, null);
        }
Exemplo n.º 9
0
 /// <summary>
 /// Sends the players's name from the client to the server
 /// </summary>
 /// <param name="name"></param>
 public void SendPlayerName(string name)
 {
     // as long as the socket is not null, BeginSend
     if (!ReferenceEquals(socket, null))
     {
         name = name.ToUpper();
         socket.BeginSend("PLAY " + name + "\n", (ex, p) => { }, null);
         playerName = name;
         socket.BeginReceive(LineReceived, null);
     }
 }
Exemplo n.º 10
0
        public void TestStopMessage()
        {
            BoggleServer.Server server = new BoggleServer.Server(2000, new string[] { "2", "Dictionary.txt", "potscatscarsteps" });

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

            StringSocket client1 = Client.CreateClient(2000);

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

            StringSocket client2 = Client.CreateClient(2000);

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

            // Receives the start message
            client1.BeginReceive(ReceiveClient1, "Client1");

            // Receives the start message
            client2.BeginReceive(ReceiveClient2, "Client2");

            // Words are added to test all aspects of the stop message
            client1.BeginSend("word pots\n", (e, o) => { }, "Client1");
            client2.BeginSend("word pots\n", (e, o) => { }, "Client2");
            client1.BeginSend("word pot\n", (e, o) => { }, "Client1");
            client2.BeginSend("word cat\n", (e, o) => { }, "Client2");
            client1.BeginSend("word pasdfasdf\n", (e, o) => { }, "Client1");
            client2.BeginSend("word aldsffas\n", (e, o) => { }, "Client2");
            client2.BeginSend("word sto\n", (e, o) => { }, "Client2");

            // Waits until stop message for both clients have been received before asserting
            do
            {
                client1.BeginReceive(ReceiveStop1, "Client1");

                client2.BeginReceive(ReceiveStop2, "Client2");
            }while (stop1 == false || stop2 == false);

            // Make sure Client 1 gets the score message
            Assert.AreEqual(true, mre3.WaitOne(timeout), "Timed out waiting 3");
            Assert.AreEqual("STOP", s3.Substring(0, 4));

            // Makes sure Client 2 gets the score message
            Assert.AreEqual("STOP", s4.Substring(0, 4));

            System.Threading.Thread.Sleep(1001);

            // Closes the server
            server.CloseServer();
        }
        /// <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;
        }
Exemplo n.º 12
0
        public void TestAllWordScores()
        {
            BoggleServer.Server server = new BoggleServer.Server(2000, new string[] { "20", "Dictionary.txt", "abansnodmodejjsm" });

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

            StringSocket client1 = Client.CreateClient(2000);

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

            StringSocket client2 = Client.CreateClient(2000);

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

            client1.BeginReceive(ReceiveClient1, "Client1");

            client2.BeginReceive(ReceiveClient2, "Client2");

            client1.BeginSend("words abandons\n", (e, o) => { }, "Client1");
            client1.BeginSend("word abandon\n", (e, o) => { }, "Client1");
            client1.BeginSend("word abandons\n", (e, o) => { }, "Client1");
            client1.BeginSend("word mode\n", (e, o) => { }, "Client1");
            client1.BeginSend("word modem\n", (e, o) => { }, "Client1");
            client1.BeginSend("word modems\n", (e, o) => { }, "Client1");
            client1.BeginSend("word mod\n", (e, o) => { }, "Client1");
            client1.BeginSend("word abandons\n", (e, o) => { }, "Client1");

            do
            {
                client1.BeginReceive(ReceiveScore1, "Client1");
            }while (!s3.Equals("SCORE 23 0"));



            // Make sure client 1 gets start message
            Assert.AreEqual(true, mre1.WaitOne(timeout), "Timed out waiting 1");
            Assert.AreEqual("START", s1.Substring(0, 5));
            Assert.AreEqual("Client1", p1);

            // Make sure client 2 gets start message
            Assert.AreEqual(true, mre2.WaitOne(timeout), "Timed out waiting 2");
            Assert.AreEqual("START", s2.Substring(0, 5));
            Assert.AreEqual("Client2", p2);

            // Make sure Client 1 gets the score message
            Assert.AreEqual(true, mre3.WaitOne(timeout), "Timed out waiting 3");
            Assert.AreEqual("SCORE 23 0", s3, "Score passed Incorrectly");

            // Closes the server
            server.CloseServer();
        }
Exemplo n.º 13
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();
        }
Exemplo n.º 14
0
        /// <summary>
        /// This callback method is called when a name has been received from the connected client.
        /// </summary>
        private void NameReceived(string name, Exception e, object payload)
        {
            StringSocket ss = (StringSocket)payload;

            // Check that the received string starts with "PLAY " followed by at least one non-whitespace character.
            if (name.StartsWith("PLAY ") && name.Substring(5).Trim().Length > 0)
            {
                name = name.Substring(5);

                lock (players)
                {
                    // Add the player to the queue.
                    players.Enqueue(new Player(ss, name));

                    // If there are two players in the queue, start a new boggle game and dequeue them.
                    if (players.Count == 2)
                    {
                        BoggleGame game = new BoggleGame(players.Dequeue(), players.Dequeue(), time, letters, ref dictionary);
                    }
                }
            }
            // Otherwise, the client deviated from protocol. Send an IGNORING message.
            else
            {
                ss.BeginSend("IGNORING " + name + "\n", (ee, pp) => { }, ss);
            }
        }
Exemplo n.º 15
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();
                }
            }
Exemplo n.º 16
0
        public void CreateNewGameOnePlayer()
        {
            BoggleServer.Server server = new BoggleServer.Server(2000, new string[] { "200", "Dictionary.txt" });

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

            StringSocket client1 = Client.CreateClient(2000);

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

            client1.BeginReceive(ReceiveClient1, "Client1");

            // Make sure client 1 times out since no messages will be sent by server
            Assert.AreEqual(false, mre1.WaitOne(timeout), "Timed out waiting 1");

            //Now that second player has connected and added name, client 1 shouldn't time out
            StringSocket client2 = Client.CreateClient(2000);

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

            //Make sure game has started
            Assert.AreEqual(true, mre1.WaitOne(timeout), "Timed out waiting 1");
            Assert.AreEqual("START", s1.Substring(0, 5));
            Assert.AreEqual("Client1", p1);

            server.CloseServer();
        }
Exemplo n.º 17
0
            public void run(int port)
            {
                int         LIMIT = 1000;
                Socket      s1, s2;
                TcpListener server;

                OpenSockets(port, out server, out s1, out s2);
                List <int> lines = new List <int>();

                try
                {
                    StringSocket sender   = new StringSocket(s1, new UTF8Encoding());
                    StringSocket receiver = new StringSocket(s2, new UTF8Encoding());
                    for (int i = 0; i < LIMIT; i++)
                    {
                        receiver.BeginReceive((s, e, p) => { lock (lines) { lines.Add(Int32.Parse(s)); } }, null);
                    }
                    for (int i = 0; i < LIMIT; i++)
                    {
                        String s = i.ToString();
                        ThreadPool.QueueUserWorkItem(x =>
                                                     sender.BeginSend(s + "\n", (e, p) => { }, null));
                    }
                    SpinWait.SpinUntil(() => { lock (lines) { return(lines.Count == LIMIT); } });
                    lines.Sort();
                    for (int i = 0; i < LIMIT; i++)
                    {
                        Assert.AreEqual(i, lines[i]);
                    }
                }
                finally
                {
                    CloseSockets(server, s1, s2);
                }
            }
Exemplo n.º 18
0
            public void run(int port)
            {
                int         LIMIT = 1000;
                Socket      s1, s2;
                TcpListener server;

                OpenSockets(port, out server, out s1, out s2);
                String[]         lines = new String[LIMIT];
                ManualResetEvent mre   = new ManualResetEvent(false);
                int count = 0;

                try
                {
                    StringSocket sender   = new StringSocket(s1, new UTF8Encoding());
                    StringSocket receiver = new StringSocket(s2, new UTF8Encoding());
                    for (int i = 0; i < LIMIT; i++)
                    {
                        receiver.BeginReceive((s, e, p) => { lines[(int)p] = s; Interlocked.Increment(ref count); }, i);
                    }
                    for (int i = 0; i < LIMIT; i++)
                    {
                        sender.BeginSend(i.ToString() + "\n", (e, p) => { }, null);
                    }
                    SpinWait.SpinUntil(() => count == LIMIT);
                    for (int i = 0; i < LIMIT; i++)
                    {
                        Assert.AreEqual(i.ToString(), lines[i]);
                    }
                }
                finally
                {
                    CloseSockets(server, s1, s2);
                }
            }
Exemplo n.º 19
0
            public void run(int port)
            {
                Socket      s1, s2;
                TcpListener server;

                OpenSockets(port, out server, out s1, out s2);
                String           line = "";
                ManualResetEvent mre  = new ManualResetEvent(false);

                try
                {
                    StringSocket sender   = new StringSocket(s1, new UTF8Encoding());
                    StringSocket receiver = new StringSocket(s2, new UTF8Encoding());
                    foreach (char c in "Hello\n")
                    {
                        sender.BeginSend(c.ToString(), (e, p) => { }, null);
                    }
                    receiver.BeginReceive((s, e, p) => { line = s; mre.Set(); }, null);
                    mre.WaitOne();
                    Assert.AreEqual("Hello", line);
                }
                finally
                {
                    CloseSockets(server, s1, s2);
                }
            }
Exemplo n.º 20
0
            public void run(int port)
            {
                Socket      s1, s2;
                TcpListener server;

                OpenSockets(port, out server, out s1, out s2);
                String           line = "";
                ManualResetEvent mre  = new ManualResetEvent(false);

                try
                {
                    StringSocket  sender   = new StringSocket(s1, new UTF8Encoding());
                    StringSocket  receiver = new StringSocket(s2, new UTF8Encoding());
                    StringBuilder text     = new StringBuilder();
                    for (int i = 0; i < 100000; i++)
                    {
                        text.Append(i);
                    }
                    String str = text.ToString();
                    text.Append('\n');
                    sender.BeginSend(text.ToString(), (e, p) => { }, null);
                    receiver.BeginReceive((s, e, p) => { line = s; mre.Set(); }, null);
                    mre.WaitOne();
                    Assert.AreEqual(str, line);
                }
                finally
                {
                    CloseSockets(server, s1, s2);
                }
            }
Exemplo n.º 21
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));
                }
            }
        }
Exemplo n.º 22
0
        /// <summary>
        /// Receives the first line of text from the client, which contains the name of the new
        /// boggle player.  Uses it to compose and send back a welcome message.
        ///
        /// Expects a "PLAY @" message after a new user has connected
        ///
        /// Invariant: the object parameter will always be a String Socket
        /// </summary>
        /// <param name="name">The string input from player</param>
        /// <param name="exception">A possible exception</param>
        /// <param name="payload">A String Socket</param>
        /// <citation>Chat Server from Lab Examples</citation>
        private void ReceiveNameCallback(String name, Exception exception, object payload)
        {
            StringSocket ss = (StringSocket)payload;   // invariant safe to cast as string socket

            // If the name is null or empty, it is invalid
            if (ReferenceEquals(null, name) || name.Equals(""))
            {
                ss.BeginSend("IGNORING\n", (e, o) => { }, ss);
                return;
            }

            // If the reference is non-null, then there was a bad connection.
            if (!ReferenceEquals(null, exception))
            {
                ss.BeginSend("IGNORING " + name + "\n", (e, o) => { }, ss);
                return;
            }

            // make the player name uppercase
            name = name.ToUpper();

            // If name doesn't start with PLAY, return
            if (!(name.StartsWith("PLAY ")))
            {
                ss.BeginSend("IGNORING " + name + "\n", (e, o) => { }, ss);
                return;
            }

            string playerName = name.Substring(5); // use this to store the actual name of the player

            // Create new player using playerName
            Player player = new Player(playerName, ss);

            lock (lockObject)
            {
                if (ReferenceEquals(null, waitingPlayer))
                {
                    waitingPlayer = player;
                }
                else
                {
                    Game game = new Game(waitingPlayer, player, gameLength, initialBoggleBoard, legalWords);
                    game.Start();
                    waitingPlayer = null;
                }
            }
        }
Exemplo n.º 23
0
        public void Test_Port_ASCII_JIM2000() //ASCII code for JIM is 747377
        {
            for (int counter = 0; counter < 5; counter++)
            {
                String[] sA     = new String[26];
                object[] pA     = new object[26];
                String   tester = "Hello world This is a test";

                // Create and start a server and client.
                TcpListener server = null;
                TcpClient   client = null;

                try
                {
                    server = new TcpListener(IPAddress.Any, ('J' + 'I' + 'M' + 2000));
                    server.Start();
                    client = new TcpClient("localhost", ('J' + 'I' + 'M' + 2000));

                    // 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
                    ManualResetEvent mre1 = new ManualResetEvent(false);
                    ManualResetEvent mre2 = new ManualResetEvent(false);

                    // Make two receive requests
                    for (int i = 0; i < tester.Length; i++)
                    {
                        receiveSocket.BeginReceive((s, o, p) => { sA[i] = s; pA[i] = p; }, i);
                    }

                    // Now send the data.  Hope those receive requests didn't block!
                    String msg = "H\ne\nl\nl\no\n \nw\no\nr\nl\nd\n \nT\nh\ni\ns\n \ni\ns\n \na\n \nt\ne\ns\nt\n";
                    foreach (char c in msg)
                    {
                        sendSocket.BeginSend(c.ToString(), (e, o) => { }, null);
                    }

                    // Make sure the lines were received properly.
                    for (int i = 0; i < tester.Length; i++)
                    {
                        Assert.AreEqual(true, mre1.WaitOne(150), "Timed out waiting for char" + sA[i] + " (" + (i + 1) + ")");
                        Assert.AreEqual(tester[i], sA[i]);
                        Assert.AreEqual(i, pA[i]);
                    }
                }
                finally
                {
                    server.Stop();
                    client.Close();
                }
            }
        }
Exemplo n.º 24
0
        private void ConnectToGame2()
        {
            TcpClient tcpClient = new TcpClient("localhost", 2000);

            socketString2 = new StringSocket(tcpClient.Client, UTF8Encoding.Default);
            socketString2.BeginSend("PLAY " + name, (o, p) => { }, name);
            //socketString2.BeginReceive(Received, socketString2);
        }
Exemplo n.º 25
0
        public void ParseCommand(string word, StringSocket sendingSocket)
        {
            // Ensures that the word is not null
            if (word != null)
            {
                // Trims the word to make sure there is no extra white space
                word = word.Trim().ToLower();

                // Variables set up to see if the score changed
                int p1TempScore, p2TempScore;

                // bool variables are set up to see which client sent the word
                bool player1;
                bool player2;

                // bool variables are set depending on who sent the word command
                player1 = (sendingSocket == p1);
                player2 = (sendingSocket == p2);

                // String is split at the space in order to evaluate the command
                string[] splitCommand = word.Split(' ');

                // If the command that was passed was "word", it processes the word
                if (splitCommand[0] == "word")
                {
                    // Checks to see if the word is less than 3 characters long before processing it
                    if (splitCommand[1].Length >= 3)
                    {
                        p1TempScore = p1Score;
                        p2TempScore = p2Score;

                        // If player 1 sent the word, processes the word as such
                        if (player1 == true)
                        {
                            processScore(splitCommand[1], p1Words, p2Words, p1Illegal, p2Illegal, ref p1Score, ref p2Score);
                        }
                        // Else if player 2 sent the word, processes the word as such
                        else if (player2 == true)
                        {
                            processScore(splitCommand[1], p2Words, p1Words, p2Illegal, p1Illegal, ref p2Score, ref p1Score);
                        }

                        if (p1TempScore != p1Score || p2TempScore != p2Score)
                        {
                            // After the word has been processed, sends the updated score to both of the clients
                            p1.BeginSend("SCORE " + p1Score + " " + p2Score + "\n", (a, b) => { }, false);
                            p2.BeginSend("SCORE " + p2Score + " " + p1Score + "\n", (a, b) => { }, false);
                        }
                    }
                }

                // Else, the client is sent the "Ignoring" command to tell the client that they were not following protocol
                else
                {
                    sendingSocket.BeginSend("IGNORING" + splitCommand[0] + "\n", (a, b) => { }, false);
                }
            }
        }
Exemplo n.º 26
0
            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 three receive requests
                    receiveSocket.BeginReceive(ReceiveEmpty, 1);
                    receiveSocket.BeginReceive(ReceiveString, 2);
                    receiveSocket.BeginReceive(ReceiveEmpty, 1);

                    // Send multiple new lines mixing both carriage and newline characters
                    String msg = "\nHelloWorld\r\n\r\n";
                    foreach (char c in msg)
                    {
                        sendSocket.BeginSend(c.ToString(), (e, o) => { }, null);
                    }

                    // Make sure empty string with \n
                    Assert.AreEqual(true, mre1.WaitOne(timeout), "Timed out waiting 1");
                    Assert.AreEqual("", s1);
                    Assert.AreEqual(1, p1);

                    //Make sure full string with \r
                    Assert.AreEqual(true, mre2.WaitOne(timeout), "Timed out waiting 2");
                    Assert.AreEqual("HelloWorld", s2);
                    Assert.AreEqual(2, p2);

                    //Make sure empty string with \r
                    Assert.AreEqual(true, mre1.WaitOne(timeout), "Timed out waiting 1");
                    Assert.AreEqual("", s1);
                    Assert.AreEqual(1, p1);
                }
                finally
                {
                    server.Stop();
                    client.Close();
                }
            }
Exemplo n.º 27
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));
                }
            }
        }
Exemplo n.º 28
0
        /// <summary>
        /// call back for receiving a word
        /// </summary>
        /// <remarks>
        /// 1. gets actual word off of received stuff
        /// 2. checks against dictionary and board
        /// 3. checks against other player (removes and adds to common if matched)
        /// 4.in case of failure (npot in dictionary or board) adds to player's penalty list
        /// </remarks>
        /// <param name="s">string received</param>
        /// <param name="e"></param>
        /// <param name="payload"></param>
        private void ProcessReceive(string s, Exception e, object payload)
        {
            //if someone disconnects, tell their opponent
            if (object.ReferenceEquals(s, null))            // && object.ReferenceEquals(e, null))
            {
                player offender = (payload as player);
                offender.PlayerSocket.Close();
                if (ReferenceEquals(offender, player1))
                {
                    player2.PlayerSocket.BeginSend("TERMINATED\n", (ee, pp) => { player2.PlayerSocket.Close(); }, null);
                }
                else
                {
                    player1.PlayerSocket.BeginSend("TERMINATED\n", (ee, pp) => { player1.PlayerSocket.Close(); }, null);
                }
                return;
            }
            else if (!object.ReferenceEquals(e, null))
            {
                throw e; // Maybe we need to do something different here that doens't stop the server. Like just remove this game from games.
            }
            // Or maybe it is just showing another issue.

            if (s.StartsWith("WORD"))
            {
                lock (processingKey)
                {
                    string tempWord   = s.Substring(5).TrimEnd('\r').ToUpper();
                    player tempPlayer = (payload as player);

                    if (BoggleServer.WordDictionary.Contains(tempWord) && board.CanBeFormed(tempWord))
                    {
                        tempPlayer.Valids.Add(tempWord);
                        if (player1.Valids.Contains(tempWord) && player2.Valids.Contains(tempWord))
                        {
                            player1.Valids.Remove(tempWord);
                            player2.Valids.Remove(tempWord);
                            common.Add(tempWord);
                        }
                        updateScore();
                        //(payload as player).PlayerSocket.BeginReceive(ProcessReceive, (payload as player));
                    }
                    else
                    {
                        tempPlayer.Penalties.Add(tempWord);
                        updateScore();
                        //(payload as player).PlayerSocket.BeginReceive(ProcessReceive, (payload as player));
                    }
                }
            }
            else
            {
                StringSocket temp = (payload as player).PlayerSocket;
                temp.BeginSend("IGNORING " + s + "\n", (ee, pp) => { }, null);
            }
            (payload as player).PlayerSocket.BeginReceive(ProcessReceive, (payload as player));
        }
Exemplo n.º 29
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, String name)
 {
     if (socket == null)
     {
         TcpClient client = new TcpClient(hostname, port);
         socket = new StringSocket(client.Client, UTF8Encoding.Default);
         socket.BeginSend(name + "\n", (e, p) => { }, null);
         socket.BeginReceive(LineReceived, null);
     }
 }
Exemplo n.º 30
0
        public void JaromAndSarahNonBlockingTest()
        {
            TcpListener server = new TcpListener(IPAddress.Any, 4002);

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

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

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

            sendSocket.BeginSend("This test wa", (e, p) => { }, 1);
            sendSocket.BeginSend("s made by\n", (e, p) => { }, 2);
            sendSocket.BeginSend("Jarom and Sarah!\n", (e, p) => { }, 3);

            receiveSocket.BeginReceive(BlockingTestCallback1, 4);
            receiveSocket.BeginReceive(BlockingTestCallback2, 5);
        }