Пример #1
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();
        }
Пример #2
0
 public HttpRequest(StringSocket socket)
 {
     this.socket        = socket;
     this.contentLength = 0;
     this.lineCount     = 0;
     socket.BeginReceive(LineReceived, socket);
 }
Пример #3
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);
                }
            }
Пример #4
0
 public player(StringSocket _playerSocket, string _playerName)
 {
     PlayerSocket = _playerSocket;
     PlayerName   = _playerName;
     Valids       = new HashSet <string>();
     Penalties    = new HashSet <string>();
 }
Пример #5
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);
                }
            }
Пример #6
0
        public void TestStartRandomDice()
        {
            string[] toArgs = new string[2];
            toArgs[0] = "5";
            toArgs[1] = "..\\..\\..\\dictionary.txt";

            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) => { clients[0].BeginReceive((s, ee, pp) => { clientString0 = s; }, 1); }, 1);
            Thread.Sleep(1250);

            clients[1].BeginSend("PLAY YY\n", (e, p) => { clients[1].BeginReceive((s, ee, pp) => { clientString1 = s; }, 1); }, 1);
            Thread.Sleep(1250);
            string boardtemp = clientString0.Substring(6, 16);

            Assert.AreEqual("START " + boardtemp + " " + toArgs[0] + " YY", clientString0);
            Assert.AreEqual("START " + boardtemp + " " + toArgs[0] + " Dylan", clientString1);
        }
Пример #7
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();
                }
            }
Пример #8
0
 /// <summary>
 /// Creates a new player with the given StringSocket and nameMsg
 /// </summary>
 /// <param nameMsg="socket">the StringSocket used to communicate with this player</param>
 /// <param nameMsg="nameMsg">The nameMsg of this player</param>
 public Player(StringSocket socket, String name)
 {
     Socket       = socket;
     Name         = name;
     ValidWords   = new HashSet <String>();
     InvalidWords = new HashSet <String>();
 }
Пример #9
0
        /// <summary>
        /// Connect to the server at the given hostname and port and with the give name.
        /// </summary>
        public void Connect(string hostname)
        {
            // if the socket is not null, just return
            if (socket != null)
            {
                return;
            }
            try
            {
                // connect to port 2000 (Boggle Server port)
                client = new TcpClient(hostname, 2000);

                // if connection works, create a new StringSocket with the client
                socket = new StringSocket(client.Client, UTF8Encoding.Default);

                // then use socket to begin receiving messages from server
                socket.BeginReceive(LineReceived, null);

                // if connection is successful, confirm it with a connection event
                ConnectionEvent(true);
            }
            catch (Exception)
            {
                // If there is a problem connecting to the server, send a new connection
                // event to the view indicating that the connection failed
                ConnectionEvent(false);
            }
        }
Пример #10
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();
        }
Пример #11
0
            public void run(int port)
            {
                Socket      s1, s2;
                TcpListener server;

                OpenSockets(port, out server, out s1, out s2);
                object           payload  = null;
                ManualResetEvent mre      = new ManualResetEvent(false);
                StringSocket     receiver = null;
                SS sender = null;

                try
                {
                    sender   = new SS(s1, new UTF8Encoding());
                    receiver = new StringSocket(s2, new UTF8Encoding());
                    sender.BeginSend("Hello\n", (e, p) => { }, null);
                    receiver.BeginReceive((s, e, p) => { payload = p; mre.Set(); }, "Payload");
                    mre.WaitOne();
                    Assert.AreEqual("Payload", payload);
                }
                finally
                {
                    CloseSockets(server, receiver, sender);
                }
            }
Пример #12
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);
                }
            }
Пример #13
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("PLAY Basil\n", (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();
                }
            }
Пример #14
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);
                }
            }
Пример #15
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();
        }
Пример #16
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);
        }
Пример #17
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));
                }
            }
        }
Пример #18
0
        /// <summary>
        /// Called when a connection has been received on port 2000.
        /// </summary>
        /// <param name="result">Result of BeginAcceptSocket</param>
        private void ConnectionRequested(IAsyncResult result)
        {
            // ConnectionRequested is invoked when the server is closed due to the BeginAcceptSocket
            // loop, however the code below will throw an exception due to null values. This try/catch
            // simply allows the server to close during debugging without being stopped by an exception.
            try
            {
                // Create a StringSocket with the client.
                Socket       s  = server.EndAcceptSocket(result);
                StringSocket ss = new StringSocket(s, Encoding.UTF8);

                // Print client connection info
                IPAddress clientIP = ((IPEndPoint)s.RemoteEndPoint).Address;
                Console.WriteLine(string.Format("{0, -23} {1, -31} {2}", "CONNECTION RECEIVED", clientIP, DateTime.Now));

                // Create a nameless Player object and pass it as the payload to BeginReceive.
                // Begin listening for messages from the client.
                Player newPlayer = new Player(null, clientIP, ss);
                ss.BeginReceive(ReceivedMessage, newPlayer);

                // Begin listening for another connection.
                server.BeginAcceptSocket(ConnectionRequested, server);
            }
            catch (ObjectDisposedException)
            {
                return;
            }
        }
Пример #19
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);
            }
        }
Пример #20
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);
                }
            }
Пример #21
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();
                }
            }
        }
Пример #22
0
 /// <summary>
 /// Constructs a View object
 /// </summary>
 public View()
 {
     InitializeComponent();
     tc = new TcpClient("155.97.209.239", 2000);
     ss = new StringSocket(tc.Client, new UTF8Encoding());
     ss.BeginReceive(messageReceived, ss);
     this.FormClosing += Closing;
 }
Пример #23
0
        /// <summary>
        /// Deals with connection requests
        /// </summary>
        private void ConnectionReceived(IAsyncResult ar)
        {
            Socket       socket = server.EndAcceptSocket(ar);
            StringSocket ss     = new StringSocket(socket, UTF8Encoding.Default);

            ss.BeginReceive(NameReceived, ss);
            server.BeginAcceptSocket(ConnectionReceived, null);
        }
Пример #24
0
        /// <summary>
        /// Receives web connections and sets up a Begin Receive for the socket
        /// </summary>
        /// <param name="ar">Async result</param>
        private void WebConnectionReceived(IAsyncResult ar)
        {
            Socket       acceptSocket     = webServer.EndAcceptSocket(ar);
            StringSocket connectionSocket = new StringSocket(acceptSocket, UTF8Encoding.Default);

            connectionSocket.BeginReceive(HttpRequestReceived, connectionSocket);
            webServer.BeginAcceptSocket(WebConnectionReceived, null);
        }
Пример #25
0
 /// <summary>
 /// Creates a player with the given StringSocket and name.
 /// </summary>
 public Player(StringSocket ss, string name)
 {
     this.ss      = ss;
     this.name    = name;
     score        = 0;
     legalWords   = new HashSet <string>();
     illegalWords = new HashSet <string>();
 }
Пример #26
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);
        }
Пример #27
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);
                }
            }
        }
Пример #28
0
        public void TestScoringDiffSizeWords()
        {
            string[] toArgs = new string[3];
            toArgs[0] = "20";
            toArgs[1] = "..\\..\\..\\dictionary.txt";
            toArgs[2] = "SERSPATGLINESERS";
            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) => { clients[0].BeginReceive((s, ee, pp) => { clientString0 = s; }, 1); }, 1);

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

            string clientString0next = "";
            string clientString1next = "";

            //bool notDone = true;
            clients[0].BeginSend("WORD Eateries\n", (e, p) => {  }, 1);
            clients[0].BeginReceive((s, ee, pp) => { clientString0 = s; }, 1);
            //Thread.Sleep(500);
            clientString0next = catchMessage(clientString0, 6, "SCORE", clients[0]);
            //clients[1].BeginReceive((s, ee, pp) => { clientString1 = s; }, 1);
            clientString1next = catchMessage(clientString1, 6, "SCORE", clients[1]);


            Assert.AreEqual("11 0", clientString0next);
            Assert.AreEqual("0 11", clientString1next);

            // The last part of this test is not working, but it is a problem with this test as telnet shows the server is working.
            //Thread.Sleep(500);
            ////notDone = true;
            //clients[0].BeginSend("WORD line\n", (e, p) => {  }, 1);

            //clients[0].BeginReceive((s, ee, pp) => { clientString0 = s; }, 1);

            //clientString0next = catchMessage(clientString0, 6, "SCORE", clients[0]);

            //clients[1].BeginReceive((s, ee, pp) => { clientString1 = s; }, 1);

            //clientString1next = catchMessage(clientString1, 6, "SCORE", clients[1]);

            //Assert.AreEqual("12 0", clientString0next);
            //Assert.AreEqual("0 12", clientString1next);
        }
Пример #29
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();
        }
Пример #30
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();
                }
            }
        /// <summary>
        /// Callback method called when connection to server is established.
        /// Sets up the string socket and raises the connected event.
        /// </summary>
        /// <param name="result">The IAsyncResult</param>
        private void ConnectCallback(IAsyncResult result)
        {
            try {
                _client.EndConnect(result);
            }
            catch (SocketException)
            {
            }
            // Creates a StringSocket from the TcpClient.
            _socket = new StringSocket(_client.Client, Encoding.UTF8);

            Tuple<string, string, bool> args = (Tuple<string, string, bool>)result.AsyncState;

            if (args.Item3)
            {
                Create(args.Item1, args.Item2);
                return;
            }
            // We're not creating; we're joining.
            Join(args.Item1, args.Item2);
        }