Example #1
0
        /// <summary>
        /// Recieves a line from the response and get the information needed out of it.
        /// </summary>
        private void LineReceived(string s, Exception e, object payload)
        {
            lineCount++;
            Console.WriteLine(s);
            if (s != null)
            {
                if (lineCount == 1)
                {
                    Regex r = new Regex(@"^(\S+)\s+(\S+)");
                    Match m = r.Match(s);

                    //Retrieve method
                    method = m.Groups[1].Value;
                    Console.WriteLine("Method: " + m.Groups[1].Value);

                    //Retrieve url
                    url = m.Groups[2].Value;
                    Console.WriteLine("URL: " + m.Groups[2].Value);

                    //need to check if method is a GET and whether to take a part URL
                    string gameID = null;
                    string brief  = null;

                    if (method.Equals("GET") && (new Regex(@"(\/\w+\.\w+\/\w+\/\d+\?\w+\=\w+)").IsMatch(url) || new Regex(@"(\/\w+\.\w+\/\w+\/\d+)").IsMatch(url)))
                    {
                        url = SplitURL(url, out gameID, out brief);
                        Console.WriteLine(url);
                    }
                    //make sure method matches a signature in the interface
                    if (!IsMethod(method, url, out methodName))
                    {
                        SendErrorResponse();
                        return;
                    }

                    //since GET /games doesn't have a content length and we have all of the info we
                    //need from the url, execute the method here.
                    if (methodName.Equals("GameStatus"))
                    {
                        GameStatusRequestRecieved(gameID, brief);
                        return;
                    }
                }
                if (s.StartsWith("Content-Length:"))
                {
                    contentLength = Int32.Parse(s.Substring(16).Trim());
                }
                if (s == "\r")
                {
                    //Begin receiving the body of the request and execute appropriate method
                    //determined by methodName.
                    //BeginReceive(ss, contentLength, methodName);
                    ss.BeginReceive(ContentReceived, null, contentLength);
                }
                else
                {
                    ss.BeginReceive(LineReceived, null);
                }
            }
        }
Example #2
0
        public void OpponentClosedGame()
        {
            BoggleServer.Server server = new BoggleServer.Server(2000, new string[] { "200", "Dictionary.txt" });

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

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

            StringSocket client1 = Client.CreateClient(2000);

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

            StringSocket client2 = Client.CreateClient(2000);

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

            client1.BeginReceive(ReceiveClient1, "Client1");

            client2.BeginReceive(ReceiveClient2, "Client2");

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

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

            server.CloseServer();
        }
Example #3
0
        /// <summary>
        /// After sending a word to the server, we want to see what it sends back.
        /// Since the server is always sending back the time, we need a way to wait
        /// to hear back the SCORE or STOP etc. This method does that.
        /// </summary>
        /// <param name="fromReceive">the string holding data received from the server</param>
        /// <param name="substringArg">how far to index into the message(should be about the length of message type</param>
        /// <param name="client">the StringSocket doing the sending/receiving</param>
        /// <param name="messageType">The type of message we are expecting according to the protocol</param>
        /// <returns>hopefully the string we are interested in.</returns>
        private string catchMessage(string fromReceive, int substringArg, string messageType, StringSocket client)
        {
            string toReturn = "";
            bool   notDone  = true;

            while (notDone)
            {
                if (fromReceive == null)
                {
                    client.BeginReceive((s, ee, pp) => { fromReceive = s; }, 1);
                }
                else if (fromReceive.StartsWith(messageType))
                {
                    lock (client)
                    {
                        toReturn = fromReceive.Substring(substringArg);
                        notDone  = false;
                    }
                }
                else
                {
                    client.BeginReceive((s, ee, pp) => { fromReceive = s; }, 1);
                }
            }
            return(toReturn);
        }
Example #4
0
 private void LineReceived(string s, Exception e, object o)
 {
     lineCount++;
     Console.WriteLine(s);
     if (s != null)
     {
         if (lineCount == 1)
         {
             Regex r = new Regex(@"^(\S+)\s+(\S+)");
             Match m = r.Match(s);
             Console.WriteLine("Method: " + m.Groups[1].Value);
             Console.WriteLine("URL: " + m.Groups[2].Value);
         }
         if (s.StartsWith("Content-Length:"))
         {
             contentLength = Int32.Parse(s.Substring(16).Trim());
         }
         if (s == "\r")
         {
             socket.BeginReceive(ContentReceived, socket, contentLength);
         }
         else
         {
             socket.BeginReceive(LineReceived, socket);
         }
     }
 }
Example #5
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 receiver = null;
                SS           sender   = null;

                try
                {
                    sender   = new SS(s1, new UTF8Encoding());
                    receiver = new StringSocket(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, receiver, sender);
                }
            }
Example #6
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();
                }
            }
Example #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();
        }
Example #8
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);
     }
 }
Example #9
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();
        }
Example #10
0
        /// <summary>
        /// Sends a word through the string socket to the server.
        /// </summary>
        /// <param name="word"></param>
        public void SendWord(string word)
        {
            ss.BeginSend("WORD " + word + "\n", (e, o) => { }, ss);

            //Updates the list of played words.
            if (UpdateWordList != null)
            {
                UpdateWordList(word);
            }

            ss.BeginReceive(MessageReceived, ss);
        }
Example #11
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();
        }
Example #12
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 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();
                }
            }
Example #13
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;
            }
        }
Example #14
0
        /// <summary>
        /// Deal with an arriving line of text.
        /// </summary>
        private void LineReceived(String s, Exception e, object p)
        {
            //separate for different commands to each have their own event

            lock (critLock)
            {
                string test = s;

                if (s != null)
                {
                    test = test.ToUpper();

                    //start
                    if (IncomingStartEvent != null && test.Contains("START") && !(test.Contains("WORD")))
                    {
                        string line = s.Remove(0, 6);
                        IncomingStartEvent(line);
                    }

                    //score
                    if (IncomingScoreEvent != null && test.Contains("SCORE") && !(test.Contains("WORD")))
                    {
                        string line = s.Remove(0, 6);
                        IncomingScoreEvent(line);
                    }

                    //terminated
                    if (test.Length > 8)
                    {
                        if (IncomingTerminatedEvent != null && test.Contains("TERMINATED"))
                        {
                            string line = test;
                            IncomingTerminatedEvent(line);
                        }
                    }
                    //time
                    if (IncomingTimeEvent != null && test.Contains("TIME") && !(test.Contains("WORD")))
                    {
                        //trim command from string
                        string line = s.Remove(0, 4);
                        IncomingTimeEvent(line);
                    }

                    //stop
                    if (IncomingStopEvent != null && test.Contains("STOP") && !(test.Contains("WORD")))
                    {
                        string line = s.Remove(0, 4);
                        IncomingStopEvent(line);
                    }

                    //else ignoring
                }
            }

            //start receiving
            if (socket != null)
            {
                socket.BeginReceive(LineReceived, null);
            }
        }
Example #15
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);
                }
            }
Example #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();
        }
Example #17
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();
        }
Example #18
0
            public void run(int port)
            {
                TcpListener server = null;
                TcpClient   client = null;


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

                    mre1 = new ManualResetEvent(false);

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

                    Assert.AreEqual(true, mre1.WaitOne(timeout), "Timed out waiting");
                    // this will fail if the String Socket does not handle non-ASCII characters
                    Assert.AreEqual("Hêllø Ψórlđ!", msg);
                    System.Diagnostics.Debug.WriteLine(msg);
                    Assert.AreEqual(1, p1);
                }
                finally
                {
                    sendSocket.Close();
                    receiveSocket.Close();
                    server.Stop();
                    client.Close();
                }
            }
Example #19
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);
        }
Example #20
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);
            }
        }
Example #21
0
        /// <summary>
        /// Deal with an arriving line of text.
        /// </summary>
        private void LineReceived(String s, Exception e, object p)
        {
            if ((s == null && e == null) || e != null)
            {
                //this.socket.Close();
                return;
            }

            if (s.StartsWith("TIME "))
            {
                if (IncomingTimeEvent != null)
                {
                    IncomingTimeEvent(s);
                }
            }
            else
            {
                msgString = s;

                if (IncomingLineEvent != null)
                {
                    IncomingLineEvent(s);
                }
            }

            // Listen for another message.
            socket.BeginReceive(LineReceived, null);
        }
Example #22
0
 public HttpRequest(StringSocket socket)
 {
     this.socket        = socket;
     this.contentLength = 0;
     this.lineCount     = 0;
     socket.BeginReceive(LineReceived, socket);
 }
Example #23
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);
                }
            }
Example #24
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);
                }
            }
Example #25
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);
                }
            }
Example #26
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);
                }
            }
Example #27
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();
                }
            }
        }
Example #28
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;
 }
Example #29
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);
        }
Example #30
0
 /// <summary>
 /// Deal with an arriving line of text.
 /// </summary>
 private void LineReceived(String s, Exception e, object p)
 {
     if (IncomingLineEvent != null)
     {
         IncomingLineEvent(s);
     }
     socket.BeginReceive(LineReceived, null);
 }