private static void TestCase1(Socket clientSocket, IPEndPoint endPt)
        {
            Console.WriteLine("TestCase 1 Started...");

            // {REQUEST_PORT, “SVC1”, 0, 0} send message
            PRSMessage msg = new PRSMessage(PRSMessage.MESSAGE_TYPE.REQUEST_PORT, "SVC1", 0, 0);

            SendMessage(clientSocket, endPt, msg);

            // {RESPONSE, “SVC1”, 40000, SUCCESS} recieve message
            ExpectMessage(clientSocket, "{RESPONSE, SVC1, 40000, SUCCESS}");

            // {KEEP_ALIVE, “SVC1”, 40000, 0} send message
            msg = new PRSMessage(PRSMessage.MESSAGE_TYPE.KEEP_ALIVE, "SVC1", 40000, 0);
            SendMessage(clientSocket, endPt, msg);

            // {RESPONSE, “SVC1”, 40000, SUCCESS} recieve message
            ExpectMessage(clientSocket, "{RESPONSE, SVC1, 40000, SUCCESS}");

            // {CLOSE_PORT, “SVC1”, 40000, 0} send message
            msg = new PRSMessage(PRSMessage.MESSAGE_TYPE.CLOSE_PORT, "SVC1", 40000, 0);
            SendMessage(clientSocket, endPt, msg);

            // {RESPONSE, “SVC1”, 40000, SUCCESS} recieve message
            ExpectMessage(clientSocket, "{RESPONSE, SVC1, 40000, SUCCESS}");

            Console.WriteLine("TestCase 1 Passed!");
            Console.WriteLine();
        }
Exemplo n.º 2
0
        static void Main(string[] args)
        {
            string ADDRESS = "127.0.0.1";
            int    PORT    = 30000;

            // create the socket for sending messages to the server
            Socket clientSocket = new Socket(SocketType.Dgram, ProtocolType.Udp);

            Console.WriteLine("Socket created");

            // construct the server's address and port
            IPEndPoint endPt = new IPEndPoint(IPAddress.Parse(ADDRESS), PORT);

            try
            {
                // send a message to the server
                Console.WriteLine("Sending message to server...");
                PRSMessage msg = new PRSMessage();
                msg.msgType = PRSMessage.MsgType.STOP;
                byte[] buffer = msg.Serialize();
                int    result = clientSocket.SendTo(buffer, endPt);
                Console.WriteLine("Sent " + result.ToString() + " bytes: " + new string(ASCIIEncoding.UTF8.GetChars(buffer)));
            }
            catch (Exception ex)
            {
                Console.WriteLine("Exception when receiving..." + ex.Message);
            }

            // close the socket and quit
            Console.WriteLine("Closing down");
            clientSocket.Close();
            Console.WriteLine("Closed!");

            Console.ReadKey();
        }
Exemplo n.º 3
0
            private PRSMessage RequestPort(string serviceName)
            {
                PRSMessage response = null;

                if (ports.SingleOrDefault(p => p.ServiceName == serviceName && !p.Available) == null)
                {
                    // client has requested the lowest available port, so find it!
                    PortReservation reservation = null;
                    reservation = ports.FirstOrDefault(p => p.Available);

                    // if found an avialable port, reserve it and send SUCCESS
                    if (reservation != null)
                    {
                        reservation.Reserve(serviceName);
                        response = new PRSMessage(PRSMessage.MESSAGE_TYPE.RESPONSE, serviceName, reservation.Port, PRSMessage.STATUS.SUCCESS);
                    }
                    else
                    {
                        response = new PRSMessage(PRSMessage.MESSAGE_TYPE.RESPONSE, serviceName, 0, PRSMessage.STATUS.ALL_PORTS_BUSY);
                    }
                }
                else
                {
                    response = new PRSMessage(PRSMessage.MESSAGE_TYPE.RESPONSE, serviceName, 0, PRSMessage.STATUS.SERVICE_IN_USE);
                }

                return(response);
            }
Exemplo n.º 4
0
        private static void TestCase3(Socket clientSocket, IPEndPoint endPt)
        {
            // Simulates two PRS clients, SVC1 and SVC2, where SVC1 requests a port, then SVC2 requests a port and receives its own port.

            Console.WriteLine("TestCase 3 Started...");

            // send {REQUEST_PORT, “SVC1”, 0, 0}
            PRSMessage msg = new PRSMessage(PRSMessage.MESSAGE_TYPE.REQUEST_PORT, "SVC1", 0, 0);

            SendMessage(clientSocket, endPt, msg);

            // expect {RESPONSE, “SVC1”, 40000, SUCCESS}
            ExpectMessage(clientSocket, "{RESPONSE, SVC1, 40000, SUCCESS}");

            // send {REQUEST_PORT, “SVC2”, 0, 0}
            SendMessage(clientSocket, endPt, new PRSMessage(PRSMessage.MESSAGE_TYPE.REQUEST_PORT, "SVC2", 0, 0));

            // expect {RESPONSE, “SVC2”, 40000, SUCCESS}
            ExpectMessage(clientSocket, "{RESPONSE, SVC2, 40001, SUCCESS}");

            // send {CLOSE_PORT, “SVC1”, 40000, 0}
            SendMessage(clientSocket, endPt, new PRSMessage(PRSMessage.MESSAGE_TYPE.CLOSE_PORT, "SVC1", 40000, 0));

            // expect {RESPONSE, “SVC1”, 40000, SUCCESS}
            ExpectMessage(clientSocket, "{RESPONSE, SVC1, 40000, SUCCESS}");

            // send {CLOSE_PORT, “SVC2”, 40000, 0}
            SendMessage(clientSocket, endPt, new PRSMessage(PRSMessage.MESSAGE_TYPE.CLOSE_PORT, "SVC2", 40001, 0));

            // expect {RESPONSE, “SVC2”, 40000, SUCCESS}
            ExpectMessage(clientSocket, "{RESPONSE, SVC2, 40001, SUCCESS}");

            Console.WriteLine("TestCase 3 Passed!");
            Console.WriteLine();
        }
Exemplo n.º 5
0
        private static void TestCase1(Socket clientSocket, IPEndPoint endPt)
        {
            // Simulates a PRS client, SVC1, that requests a port, keeps it alive and then closes it.
            Console.WriteLine("TestCase 1 Started...");

            // send {REQUEST_PORT, “SVC1”, 0, 0}
            PRSMessage msg = new PRSMessage(PRSMessage.MESSAGE_TYPE.REQUEST_PORT, "SVC1", 0, 0);

            SendMessage(clientSocket, endPt, msg);

            // expect {RESPONSE, “SVC1”, 40000, SUCCESS}
            ExpectMessage(clientSocket, "{RESPONSE, SVC1, 40000, SUCCESS}");

            // send {KEEP_ALIVE, “SVC1”, 40000, 0}
            msg = new PRSMessage(PRSMessage.MESSAGE_TYPE.KEEP_ALIVE, "SVC1", 40000, 0);
            SendMessage(clientSocket, endPt, msg);

            // expect {RESPONSE, “SVC1”, 40000, SUCCESS}
            ExpectMessage(clientSocket, "{RESPONSE, SVC1, 40000, SUCCESS}");

            // send {CLOSE_PORT, “SVC1”, 40000, 0}
            msg = new PRSMessage(PRSMessage.MESSAGE_TYPE.CLOSE_PORT, "SVC1", 40000, 0);
            SendMessage(clientSocket, endPt, msg);

            // expect {RESPONSE, “SVC1”, 40000, SUCCESS}
            ExpectMessage(clientSocket, "{RESPONSE, SVC1, 40000, SUCCESS}");

            Console.WriteLine("TestCase 1 Passed!");
            Console.WriteLine();
        }
        private static void TestCase2(Socket clientSocket, IPEndPoint endPt)
        {
            // Simulates two PRS clients, SVC1 and C1, where SVC1 requests a port, and C1 looks up the port.

            Console.WriteLine("TestCase 2 Started...");

            // {REQUEST_PORT, “SVC1”, 0, 0} send message
            PRSMessage msg = new PRSMessage(PRSMessage.MESSAGE_TYPE.REQUEST_PORT, "SVC1", 0, 0);

            SendMessage(clientSocket, endPt, msg);

            // {RESPONSE, “SVC1”, 40000, SUCCESS} recieve message
            ExpectMessage(clientSocket, "{RESPONSE, SVC1, 40000, SUCCESS}");

            // {LOOKUP_PORT, “SVC1”, 0, 0} send message
            msg = new PRSMessage(PRSMessage.MESSAGE_TYPE.LOOKUP_PORT, "SVC1", 0, 0);
            SendMessage(clientSocket, endPt, msg);

            // {RESPONSE, “SVC1”, 40000, SUCCESS} recieve message
            ExpectMessage(clientSocket, "{RESPONSE, SVC1, 40000, SUCCESS}");

            // {CLOSE_PORT, “SVC1”, 40000, 0} send message
            msg = new PRSMessage(PRSMessage.MESSAGE_TYPE.CLOSE_PORT, "SVC1", 40000, 0);
            SendMessage(clientSocket, endPt, msg);

            // {RESPONSE, “SVC1”, 40000, SUCCESS} recieve message
            ExpectMessage(clientSocket, "{RESPONSE, SVC1, 40000, SUCCESS}");

            Console.WriteLine("TestCase 2 Passed!");
            Console.WriteLine();
        }
        private static void TestCase4(Socket clientSocket, IPEndPoint endPt)
        {
            // Simulates two PRS clients, SVC1 and SVC2, where SVC1 requests a port, SVC1 fails to keep the port alive, then SVC2 requests a port and receives SVC1’s expired port.

            Console.WriteLine("TestCase 4 Started...");

            // {REQUEST_PORT, “SVC1”, 0, 0} send message
            PRSMessage msg = new PRSMessage(PRSMessage.MESSAGE_TYPE.REQUEST_PORT, "SVC1", 0, 0);

            SendMessage(clientSocket, endPt, msg);

            // {RESPONSE, “SVC1”, 40000, SUCCESS} recieve message
            ExpectMessage(clientSocket, "{RESPONSE, SVC1, 40000, SUCCESS}");

            //sleep for 15 sec'
            Console.WriteLine("Sleeping for 15 seconds...");
            Thread.Sleep(15000);

            // {REQUEST_PORT, “SVC1”, 0, 0} send message
            msg = new PRSMessage(PRSMessage.MESSAGE_TYPE.REQUEST_PORT, "SVC2", 0, 0);
            SendMessage(clientSocket, endPt, msg);

            // {RESPONSE, “SVC2”, 40000, SUCCESS} recieve message
            ExpectMessage(clientSocket, "{RESPONSE, SVC2, 40000, SUCCESS}");

            // {REQUEST_PORT, “SVC2”, 40000, 0} send message
            msg = new PRSMessage(PRSMessage.MESSAGE_TYPE.CLOSE_PORT, "SVC2", 40000, 0);
            SendMessage(clientSocket, endPt, msg);

            // {RESPONSE, “SVC2”, 40000, SUCCESS} recieve message
            ExpectMessage(clientSocket, "{RESPONSE, SVC2, 40000, SUCCESS}");

            Console.WriteLine("TestCase 4 Passed!");
            Console.WriteLine();
        }
Exemplo n.º 8
0
            public PRSMessage ParseMessage(PRSMessage Request)//Parses through message and formulates a response to be sent back
            {
                //error checking0. SUCCESS
                //1.SERVICE_IN_USE
                //2.SERVICE_NOT_FOUND
                //3.ALL_PORTS_BUSY
                //4.INVALID_ARG
                //5.UNDEFINED_ERROR
                switch (Request.msgType)
                {
                case PRSMessage.MsgType.CLOSE_PORT:        //Closes the requested port 3 errors 2,4,5
                    return(PRSMessage.MakeRESPONSE(0, 0)); //Returns a success

                case PRSMessage.MsgType.KEEP_ALIVE:        //keeps service alive 3 errors 2,4,5
                    return(PRSMessage.MakeRESPONSE(0, 0)); //Returns a success

                case PRSMessage.MsgType.LOOKUP_PORT:       //takes a service name and gives a port error 2,4,5
                    return(PRSMessage.MakeRESPONSE(0, 0)); //Returns a success

                case PRSMessage.MsgType.REQUEST_PORT:      //Gives service lowest port 2,3,4,5
                    return(PRSMessage.MakeRESPONSE(0, 0)); //Returns a success

                case PRSMessage.MsgType.STOP:              //Server gets stopped by the Handler this sends response
                    return(PRSMessage.MakeRESPONSE(0, 0)); //Returns a success

                default:
                    return(PRSMessage.MakeRESPONSE(0, 0));   //Returns a success;
                }
            }
Exemplo n.º 9
0
            private PRSMessage portdead(PRSMessage Request)
            {
                ManagedPort p = find_port(Request.port);

                p.reserved = false;
                Console.WriteLine("Marked port dead:" + p.port);
                return(PRSMessage.MakeRESPONSE(PRSMessage.Status.SUCCESS, Request.port));
            }
Exemplo n.º 10
0
            private PRSMessage lookup_port(PRSMessage Request)
            {
                ManagedPort p = find_service(Request.serviceName);//find the service in the list

                if (p == null)
                {
                    return(PRSMessage.MakeRESPONSE(PRSMessage.Status.SERVICE_NOT_FOUND, Request.port)); //if the service isnt in the list return not found
                }
                return(PRSMessage.MakeRESPONSE(PRSMessage.Status.SUCCESS, (ushort)p.port));             //if it is return success with port number
            }
Exemplo n.º 11
0
            public PRSMessage HandleMessage(PRSMessage msg)
            {
                // TODO: PRS.HandleMessage()

                // handle one message and return a response

                PRSMessage response = null;

                switch (msg.MsgType)
                {
                case PRSMessage.MESSAGE_TYPE.REQUEST_PORT:
                {
                    // check for expired ports and send requested report
                }
                break;

                case PRSMessage.MESSAGE_TYPE.KEEP_ALIVE:
                {
                    // client has requested that we keep their port alive
                    // find the port
                    // if found, keep it alive and send SUCCESS
                    // else, SERVICE_NOT_FOUND
                }
                break;

                case PRSMessage.MESSAGE_TYPE.CLOSE_PORT:
                {
                    // client has requested that we close their port, and make it available for others!
                    // find the port
                    // if found, close it and send SUCCESS
                    // else, SERVICE_NOT_FOUND
                }
                break;

                case PRSMessage.MESSAGE_TYPE.LOOKUP_PORT:
                {
                    // client wants to know the reserved port number for a named service
                    // find the port
                    // if found, send port number back
                    // else, SERVICE_NOT_FOUND
                }
                break;

                case PRSMessage.MESSAGE_TYPE.STOP:
                {
                    // client is telling us to close the appliation down
                    // stop the PRS and return SUCCESS
                }
                break;
                }

                return(response);
            }
Exemplo n.º 12
0
        private static PRSMessage ExpectMessage(Socket clientSocket, string expectedMessage)
        {
            // receive message and validate that expected PRSMessage was received
            EndPoint   remoteEP = new IPEndPoint(IPAddress.Any, 0);
            PRSMessage msg      = PRSMessage.ReceiveMessage(clientSocket, ref remoteEP);

            if (msg.ToString() != expectedMessage)
            {
                throw new Exception("Test failed! Expected " + expectedMessage);
            }

            return(msg);
        }
Exemplo n.º 13
0
            private PRSMessage RequestPort(string serviceName)
            {
                // TODO: PRS.RequestPort()

                PRSMessage response = null;

                // client has requested the lowest available port, so find it!

                // if found an avialable port, reserve it and send SUCCESS
                // else, none available, send ALL_PORTS_BUSY

                return(response);
            }
        private static void TestCase6(Socket clientSocket, IPEndPoint endPt)
        {
            // Simulates a PRS client, M, that tells the PRS to stop
            Console.WriteLine("TestCase 6 Started...");

            // send {STOP, “”, 0, 0}
            PRSMessage msg = new PRSMessage(PRSMessage.MESSAGE_TYPE.STOP, "", 0, 0);

            SendMessage(clientSocket, endPt, msg);

            // expect {RESPONSE, “”, 0, SUCCESS}
            ExpectMessage(clientSocket, "{RESPONSE, , 0, SUCCESS}");

            Console.WriteLine("TestCase 6 Passed!");
            Console.WriteLine();
        }
Exemplo n.º 15
0
            public PRSMessage ParseMessageType(PRSMessage Request)//Parses through message and formulates a response to be sent back
            {
                //error checking
                //0. SUCCESS
                //1.SERVICE_IN_USE
                //2.SERVICE_NOT_FOUND
                //3.ALL_PORTS_BUSY
                //4.INVALID_ARG
                //5.UNDEFINED_ERROR
                try
                {
                    switch (Request.msgType)//checks the type
                    {
                    case PRSMessage.MsgType.PORT_DEAD:
                        return(portdead(Request));

                    case PRSMessage.MsgType.CLOSE_PORT:    //Closes the requested port 3 errors 2,4,5
                                                           //if service in msg is not at either the correct port or name
                                                           //throw out Response service not found
                        return(close_port(Request));

                    case PRSMessage.MsgType.KEEP_ALIVE:    //keeps service alive 3 errors 2,4,5
                                                           //if port or service is incorrect return invalid
                        return(keep_alive(Request));

                    case PRSMessage.MsgType.LOOKUP_PORT:    //takes a service name and gives a port error 2,4,5
                                                            //if not well formulated throw invalid
                                                            //if service name not correct return not found
                        return(lookup_port(Request));

                    case PRSMessage.MsgType.REQUEST_PORT:    //Gives service lowest port 1,3,4,5
                        return(request_port(Request));

                    case PRSMessage.MsgType.STOP:                                          //Server gets stopped by the Handler this sends response
                                                                                           //only checks message type
                        Console.WriteLine("Stop Has been recieved");
                        return(PRSMessage.MakeSTOP());                                     //Stop doesn't impact the port reservations so it just uses its method

                    default:                                                               //if not a correct message code
                        return(PRSMessage.MakeRESPONSE(PRSMessage.Status.INVALID_ARG, 0)); //Returns an invalid arg
                    }
                }
                catch (Exception e)
                {
                    return(PRSMessage.MakeRESPONSE(PRSMessage.Status.UNDEFINED_ERROR, 0));//if this happened the service broke
                }
            }
Exemplo n.º 16
0
            private PRSMessage keep_alive(PRSMessage Request)
            {
                //check if the service and port are both valid and match
                ManagedPort n = find_service(Request.serviceName);//checks if the service is valid

                if (n == null)
                {
                    return(PRSMessage.MakeRESPONSE(PRSMessage.Status.SERVICE_NOT_FOUND, Request.port));
                }
                ManagedPort p = find_port(Request.port);//Checks if the port is valid

                if (p == null || p != n)
                {
                    return(PRSMessage.MakeRESPONSE(PRSMessage.Status.INVALID_ARG, Request.port));
                }
                p.lastAlive = DateTime.Now;
                return(PRSMessage.MakeRESPONSE(PRSMessage.Status.SUCCESS, Request.port));
            }
        private static void TestCase5(Socket clientSocket, IPEndPoint endPt)
        {
            // Simulates two PRS clients, SVC1 and SVC2, where SVC1 requests a port, SVC1 keeps the port alive, then SVC2 requests a port and receives its own port.

            Console.WriteLine("TestCase 5 Started...");

            // send {REQUEST_PORT, “SVC1”, 0, 0}
            PRSMessage msg = new PRSMessage(PRSMessage.MESSAGE_TYPE.REQUEST_PORT, "SVC1", 0, 0);

            SendMessage(clientSocket, endPt, msg);

            // expect {RESPONSE, “SVC1”, 40000, SUCCESS}
            ExpectMessage(clientSocket, "{RESPONSE, SVC1, 40000, SUCCESS}");

            // use Thread.Sleep();
            Console.WriteLine("Sleeping for 8 sec, please be patient...");
            Thread.Sleep(8000);

            // send {KEEP_ALIVE, “SVC1”, 40000, 0}
            msg = new PRSMessage(PRSMessage.MESSAGE_TYPE.KEEP_ALIVE, "SVC1", 40000, 0);
            SendMessage(clientSocket, endPt, msg);

            // expect {RESPONSE, “SVC1”, 40000, SUCCESS}
            ExpectMessage(clientSocket, "{RESPONSE, SVC1, 40000, SUCCESS}");

            // use Thread.Sleep();
            Console.WriteLine("Sleeping for 8 sec, please be patient...");
            Thread.Sleep(8000);

            // send {REQUEST_PORT, “SVC2”, 0, 0}
            SendMessage(clientSocket, endPt, new PRSMessage(PRSMessage.MESSAGE_TYPE.REQUEST_PORT, "SVC2", 0, 0));

            // expect {RESPONSE, “SVC2”, 40000, SUCCESS}
            ExpectMessage(clientSocket, "{RESPONSE, SVC2, 40001, SUCCESS}");

            // send {CLOSE_PORT, “SVC2”, 40000, 0}
            SendMessage(clientSocket, endPt, new PRSMessage(PRSMessage.MESSAGE_TYPE.CLOSE_PORT, "SVC2", 40001, 0));

            // expect {RESPONSE, “SVC2”, 40000, SUCCESS}
            ExpectMessage(clientSocket, "{RESPONSE, SVC2, 40001, SUCCESS}");

            Console.WriteLine("TestCase 5 Passed!");
            Console.WriteLine();
        }
Exemplo n.º 18
0
            PRSHandler Handler;//Handles the messages recieved

            public void StartService(int P, int S, int E, int T)
            {
                servicePort = P;                       //Set the Service Port to listen on
                Handler     = new PRSHandler(S, E, T); //Create the handler to deal with the ports
                Socket listeningSocket = new Socket(SocketType.Dgram, ProtocolType.Udp);

                Console.WriteLine("Listening socket created");

                // bind the socket to the server port
                listeningSocket.Bind(new IPEndPoint(IPAddress.Any, servicePort));
                Console.WriteLine("Listening socket bound to port " + servicePort.ToString());
                bool done = false; //For stop message

                while (!done)      // a stop message has not been recieved
                {
                    try
                    {
                        // receive a message from a client
                        Console.WriteLine("Waiting for message from client...");
                        byte[]   buffer   = new byte[PRSMessage.SIZE];
                        EndPoint remoteEP = new IPEndPoint(IPAddress.Any, 0);
                        int      result   = listeningSocket.ReceiveFrom(buffer, ref remoteEP);
                        Console.WriteLine("Received " + result.ToString() + " bytes: " + new string(ASCIIEncoding.UTF8.GetChars(buffer)));
                        PRSMessage msg = PRSMessage.Deserialize(buffer);
                        if (msg.msgType == PRSMessage.MsgType.STOP)
                        {
                            done = true;
                        }
                        PRSMessage response = Handler.ParseMessage(msg);
                        PRSCommunicator.SendMessage(listeningSocket, remoteEP, response);
                    }
                    catch (Exception ex)
                    {
                        Console.WriteLine("Exception when receiving..." + ex.Message);
                    }
                }

                // close the socket and quit
                Console.WriteLine("Closing down");
                listeningSocket.Close();
                Console.WriteLine("Closed!");

                Console.ReadKey();
            }
Exemplo n.º 19
0
            private PRSMessage close_port(PRSMessage Request)
            {
                //check if port and name are accurate
                ManagedPort n = find_service(Request.serviceName);//checks if the service is valid

                if (n == null)
                {
                    return(PRSMessage.MakeRESPONSE(PRSMessage.Status.SERVICE_NOT_FOUND, Request.port));
                }
                ManagedPort p = find_port(Request.port);//Checks if the port is valid

                if (p == null || p != n)
                {
                    return(PRSMessage.MakeRESPONSE(PRSMessage.Status.INVALID_ARG, Request.port));
                }
                //Actually close port
                p.serviceName = null;
                p.reserved    = false;
                return(PRSMessage.MakeRESPONSE(PRSMessage.Status.SUCCESS, Request.port));
            }
Exemplo n.º 20
0
            private PRSMessage request_port(PRSMessage Request)
            {
                //check if service in use
                ManagedPort sn = find_service(Request.serviceName);                                  //if the service is in the list

                if (sn != null)                                                                      //check to see if it was found in the list
                {
                    return(PRSMessage.MakeRESPONSE(PRSMessage.Status.SERVICE_IN_USE, Request.port)); //if it was its already in use
                }
                foreach (ManagedPort p in Ports)                                                     //for each port in the list
                {
                    if (!p.reserved && p.serviceName == null)                                        //check if its reserved
                    {
                        p.reserved    = true;                                                        //reserve it
                        p.serviceName = Request.serviceName;                                         //set the service name
                        p.lastAlive   = DateTime.Now;                                                //update the time
                        return(PRSMessage.MakeRESPONSE(PRSMessage.Status.SUCCESS, (ushort)p.port));  //return success with port number
                    }
                }
                return(PRSMessage.MakeRESPONSE(PRSMessage.Status.ALL_PORTS_BUSY, Request.port));
            }
Exemplo n.º 21
0
        private static PRSMessage Handle_REQUEST_PORT(PRSMessage msg)
        {
            /*
             * validate msg arguments...
             *  if service name already has a reserved port
             *          return SERVICE_IN_USE
             *  if otherwise invalid
             *          return INVALID_ARG
             * find lowest numbered unused port
             *  reserve the chosen port
             *  set last alive to now
             *  return SUCCESS and the chosen port
             * if no port available
             *  return ALL_PORTS_BUSY
             * if error occurs
             *  return UNDEFINED_ERROR
             */

            // return expected response type message
            return(new PRSMessage());
        }
Exemplo n.º 22
0
        private static void TestCase2(Socket clientsocket)//Lookup port dead
        {
            //TestCase 2:
            //FTP server reserves a port
            IPEndPoint endPt         = new IPEndPoint(IPAddress.Parse(PRSCommunicator.DEFAULT_IP), PRSCommunicator.DEFAULT_PORT);
            string     FTPServer     = "FTP";
            ushort     allocatedport = 0;
            ushort     requestedport = 0;

            //Send request port
            PRSCommunicator.SendMessage(clientsocket, endPt, PRSMessage.MakeREQUEST_PORT(FTPServer));
            IPEndPoint remoteEP  = new IPEndPoint(IPAddress.Any, 0);
            PRSMessage statusMsg = PRSCommunicator.ReceiveMessage(clientsocket, ref remoteEP);

            //PRSCommunicator.PrintMessage(statusMsg);
            if (statusMsg.status != PRSMessage.Status.SUCCESS)
            {
                throw new Exception("TestCase2 failed on Request Port");
            }
            allocatedport = statusMsg.port;
            Console.WriteLine("Allocated port of " + allocatedport.ToString());
            //FTP Client asks for the port that the client is on
            PRSCommunicator.SendMessage(clientsocket, endPt, PRSMessage.MakeLOOKUP_PORT("FTP"));
            //FTP Client "attempts" to connect to server
            statusMsg = PRSCommunicator.ReceiveMessage(clientsocket, ref remoteEP);
            if (statusMsg.status != PRSMessage.Status.SUCCESS)
            {
                throw new Exception("TestCase2 failed on LookupPort");
            }
            requestedport = statusMsg.port;
            Console.WriteLine("Service is on port: " + allocatedport.ToString());
            //FTP Client fails to connect
            //FTP client sends port dead to PRS
            PRSCommunicator.SendMessage(clientsocket, endPt, PRSMessage.MakePORT_DEAD(requestedport));
            statusMsg = PRSCommunicator.ReceiveMessage(clientsocket, ref remoteEP);
            if (statusMsg.status != PRSMessage.Status.SUCCESS)
            {
                throw new Exception("TestCase2 failed on Deadport");
            }
        }
Exemplo n.º 23
0
            private PRSMessage RequestPort(string serviceName)
            {
                PRSMessage response = null;

                // client has requested the lowest available port, so find it!

                PortReservation reservation = ports.FirstOrDefault(port => port.Available);

                if (reservation != null)
                {
                    // if found an available port, reserve it and send SUCCESS
                    reservation.Reserve(serviceName);
                    response = new PRSMessage(PRSMessage.MESSAGE_TYPE.RESPONSE, serviceName, reservation.Port, PRSMessage.STATUS.SUCCESS);
                }
                else
                {
                    // else, none available, send ALL_PORTS_BUSY
                    response = new PRSMessage(PRSMessage.MESSAGE_TYPE.RESPONSE, serviceName, 0, PRSMessage.STATUS.ALL_PORTS_BUSY);
                }

                return(response);
            }
Exemplo n.º 24
0
        private static void TestCase1(Socket clientsocket)
        {
            //TestCase 1:
            //FTP server requests port from prs
            //recieves port number
            //ftp server sends close port
            //recieves success
            IPEndPoint endPt         = new IPEndPoint(IPAddress.Parse(PRSCommunicator.DEFAULT_IP), PRSCommunicator.DEFAULT_PORT);
            string     FTPServer     = "FTP";
            ushort     allocatedport = 0;

            //Send request port
            PRSCommunicator.SendMessage(clientsocket, endPt, PRSMessage.MakeREQUEST_PORT(FTPServer));
            IPEndPoint remoteEP  = new IPEndPoint(IPAddress.Any, 0);
            PRSMessage statusMsg = PRSCommunicator.ReceiveMessage(clientsocket, ref remoteEP);

            //PRSCommunicator.PrintMessage(statusMsg);
            if (statusMsg.status != PRSMessage.Status.SUCCESS)
            {
                throw new Exception("TestCase1 failed on Request Port");
            }
            allocatedport = statusMsg.port;
            Console.WriteLine("Allocated port of " + allocatedport.ToString());
            PRSCommunicator.SendMessage(clientsocket, endPt, PRSMessage.MakeKEEP_ALIVE(FTPServer, allocatedport));

            statusMsg = PRSCommunicator.ReceiveMessage(clientsocket, ref remoteEP);
            //PRSCommunicator.PrintMessage(statusMsg);
            if (statusMsg.status != PRSMessage.Status.SUCCESS)
            {
                throw new Exception("TestCase1 failed on Keep Alive");
            }
            PRSCommunicator.SendMessage(clientsocket, endPt, PRSMessage.MakeCLOSE_PORT(FTPServer, allocatedport));
            statusMsg = PRSCommunicator.ReceiveMessage(clientsocket, ref remoteEP);
            //PRSCommunicator.PrintMessage(statusMsg);
            if (statusMsg.status != PRSMessage.Status.SUCCESS)
            {
                throw new Exception("TestCase1 failed on ClosePort");
            }
        }
Exemplo n.º 25
0
            public PRSMessage HandleMessage(PRSMessage msg)
            {
                // handle one message and return a response

                PRSMessage response = null;

                //check for expired ports
                CheckForExpiredPorts();

                switch (msg.MsgType)
                {
                case PRSMessage.MESSAGE_TYPE.REQUEST_PORT:
                {
                    //try to reserve requested port and send requested port back in response
                    response = RequestPort(msg.ServiceName);
                }
                break;

                case PRSMessage.MESSAGE_TYPE.KEEP_ALIVE:
                {
                    // client has requested that we keep their port alive
                    // find the reserved port by port# and service name
                    PortReservation reservation = ports.FirstOrDefault(p => !p.Available && p.ServiceName == msg.ServiceName && p.Port == msg.Port);

                    // if found, keep it alive and send SUCCESS else
                    if (reservation != null)
                    {
                        reservation.KeepAlive();
                        response = new PRSMessage(PRSMessage.MESSAGE_TYPE.RESPONSE, reservation.ServiceName, reservation.Port, PRSMessage.STATUS.SUCCESS);
                    }
                    else
                    {
                        response = new PRSMessage(PRSMessage.MESSAGE_TYPE.RESPONSE, msg.ServiceName, 0, PRSMessage.STATUS.SERVICE_NOT_FOUND);
                    }
                }
                break;

                case PRSMessage.MESSAGE_TYPE.CLOSE_PORT:
                {
                    // client has requested that we close their port
                    // find the reserved port by port# and service name
                    PortReservation reservation = ports.FirstOrDefault(p => !p.Available && p.ServiceName == msg.ServiceName && p.Port == msg.Port);

                    // if found, keep it alive and send SUCCESS else
                    if (reservation != null)
                    {
                        reservation.Close();
                        response = new PRSMessage(PRSMessage.MESSAGE_TYPE.RESPONSE, msg.ServiceName, reservation.Port, PRSMessage.STATUS.SUCCESS);
                    }
                    else
                    {
                        response = new PRSMessage(PRSMessage.MESSAGE_TYPE.RESPONSE, msg.ServiceName, msg.Port, PRSMessage.STATUS.SERVICE_NOT_FOUND);
                    }
                }
                break;

                case PRSMessage.MESSAGE_TYPE.LOOKUP_PORT:
                {
                    // client wants to know the reserved port number for a named service
                    // find the port
                    PortReservation reservation = ports.FirstOrDefault(p => !p.Available && p.ServiceName == msg.ServiceName);

                    // if found, send port number back
                    // else, SERVICE_NOT_FOUND
                    if (reservation != null)
                    {
                        response = new PRSMessage(PRSMessage.MESSAGE_TYPE.RESPONSE, msg.ServiceName, reservation.Port, PRSMessage.STATUS.SUCCESS);
                    }
                    else
                    {
                        response = new PRSMessage(PRSMessage.MESSAGE_TYPE.RESPONSE, msg.ServiceName, msg.Port, PRSMessage.STATUS.SERVICE_NOT_FOUND);
                    }
                }
                break;

                case PRSMessage.MESSAGE_TYPE.STOP:
                {
                    // client is telling us to close the appliation down
                    // stop the PRS and return SUCCESS
                    stopped  = true;
                    response = new PRSMessage(PRSMessage.MESSAGE_TYPE.RESPONSE, "", 0, PRSMessage.STATUS.SUCCESS);
                }
                break;
                }

                return(response);
            }
Exemplo n.º 26
0
 private static void SendMessage(Socket clientSocket, IPEndPoint endPt, PRSMessage msg)
 {
     msg.SendMessage(clientSocket, endPt);
 }
Exemplo n.º 27
0
        static void Main(string[] args)
        {
            // defaults
            ushort SERVER_PORT          = 30000;
            ushort STARTING_CLIENT_PORT = 40000;
            ushort ENDING_CLIENT_PORT   = 40099;
            int    KEEP_ALIVE_TIMEOUT   = 10; //300

            try
            {
                // -p < service port >
                // -s < starting client port number >
                // -e < ending client port number >
                // -t < keep alive time in seconds >

                for (int i = 0; i < args.Length; i++)
                {
                    if (args[i] == "-p")
                    {
                        SERVER_PORT = ushort.Parse(args[i + 1]);
                    }
                    if (args[i] == "-s")
                    {
                        SERVER_PORT = ushort.Parse(args[i + 1]);
                    }
                    if (args[i] == "-e")
                    {
                        ENDING_CLIENT_PORT = ushort.Parse(args[i + 1]);
                    }
                    if (args[i] == "-t")
                    {
                        KEEP_ALIVE_TIMEOUT = int.Parse(args[i + 1]);
                    }
                }
            }
            catch (Exception ex)
            {
                Console.WriteLine("Exception: " + ex.Message);
                Console.WriteLine(ex.StackTrace);
            }

            // initialize the PRS server
            PRS prs = new PRS(STARTING_CLIENT_PORT, ENDING_CLIENT_PORT, KEEP_ALIVE_TIMEOUT);

            // create the socket for receiving messages at the server
            Socket listeningSocket = new Socket(SocketType.Dgram, ProtocolType.Udp);

            // bind the listening socket to the PRS server port
            listeningSocket.Bind(new IPEndPoint(IPAddress.Any, SERVER_PORT));

            //
            // Process client messages
            //

            while (!prs.Stopped)
            {
                EndPoint clientEndPoint = null;
                try
                {
                    // receive a message from a client
                    clientEndPoint = new IPEndPoint(IPAddress.Any, 0);
                    PRSMessage msg = PRSMessage.ReceiveMessage(listeningSocket, ref clientEndPoint);

                    // let the PRS handle the message
                    PRSMessage response = prs.HandleMessage(msg);

                    // send response message back to client
                    response.SendMessage(listeningSocket, clientEndPoint);
                }
                catch (Exception ex)
                {
                    // attempt to send a UNDEFINED_ERROR response to the client, if we know who that was
                    if (clientEndPoint != null)
                    {
                        PRSMessage errorMsg = new PRSMessage(PRSMessage.MESSAGE_TYPE.RESPONSE, "", 0, PRSMessage.STATUS.UNDEFINED_ERROR);
                        errorMsg.SendMessage(listeningSocket, clientEndPoint);
                    }
                }
            }

            // close the listening socket
            listeningSocket.Close();
            // wait for a keypress from the user before closing the console window
            Console.WriteLine("Press Enter to exit");
            Console.ReadKey();
        }
Exemplo n.º 28
0
        static void Main(string[] args)
        {
            // TODO: interpret cmd line options

            /*
             * -p <service port>
             * -s <starting client port number>
             * -e <ending client port number>
             * -t <keep alive time in seconds>
             */

            int servicePort        = 30000;
            int startingClientPort = 40000;
            int endingClientPort   = 40099;
            int keepAlive          = 300;

            // initialize a collection of un-reserved ports to manage
            List <ManagedPort> ports = new List <ManagedPort>();

            for (int p = startingClientPort; p <= endingClientPort; p++)
            {
                ManagedPort mp = new ManagedPort();
                mp.port     = p;
                mp.reserved = false;

                ports.Add(mp);
            }

            // create the socket for receiving messages at the server
            Socket listeningSocket = new Socket(SocketType.Dgram, ProtocolType.Udp);

            Console.WriteLine("Listening socket created");

            // bind the socket to the server port
            listeningSocket.Bind(new IPEndPoint(IPAddress.Any, servicePort));
            Console.WriteLine("Listening socket bound to port " + servicePort.ToString());

            // listen for client messages
            bool done = false;

            while (!done)
            {
                try
                {
                    // receive a message from a client
                    IPEndPoint remoteEP = new IPEndPoint(IPAddress.Any, 0);
                    PRSMessage msg      = PRSCommunicator.ReceiveMessage(listeningSocket, ref remoteEP);

                    // handle the message
                    PRSMessage response = null;
                    switch (msg.msgType)
                    {
                    case PRSMessage.MsgType.REQUEST_PORT:
                        Console.WriteLine("Received REQUEST_PORT message");
                        response = Handle_REQUEST_PORT(msg);
                        break;

                    case PRSMessage.MsgType.STOP:
                        Console.WriteLine("Received STOP message");
                        done = true;
                        break;

                    default:
                        // TODO: handle unknown message type!
                        break;
                    }

                    if (response != null)
                    {
                        // send response message back to client
                        PRSCommunicator.SendMessage(listeningSocket, remoteEP, response);
                    }
                }
                catch (Exception ex)
                {
                    Console.WriteLine("Exception when receiving..." + ex.Message);
                }
            }

            // close the socket and quit
            Console.WriteLine("Closing down");
            listeningSocket.Close();
            Console.WriteLine("Closed!");

            Console.ReadKey();
        }
Exemplo n.º 29
0
        static void Main(string[] args)
        {
            string ADDRESS = "127.0.0.1";
            int    PORT    = 30000;

            // create the socket for sending messages to the server
            Socket clientSocket = new Socket(SocketType.Dgram, ProtocolType.Udp);

            Console.WriteLine("Socket created");

            // construct the server's address and port
            IPEndPoint endPt = new IPEndPoint(IPAddress.Parse(ADDRESS), PORT);

            try
            {
                string serviceName   = "foo";
                ushort allocatedPort = 0;

                // send REQUEST_PORT
                PRSCommunicator.SendMessage(clientSocket, endPt, PRSMessage.CreateREQUEST_PORT(serviceName));

                // check status
                IPEndPoint remoteEP  = new IPEndPoint(IPAddress.Any, 0);
                PRSMessage statusMsg = PRSCommunicator.ReceiveMessage(clientSocket, ref remoteEP);
                if (statusMsg.status == PRSMessage.Status.SUCCESS)
                {
                    allocatedPort = statusMsg.port;
                    Console.WriteLine("Allocated port of " + allocatedPort.ToString());
                }
                else if (statusMsg.status == PRSMessage.Status.SERVICE_IN_USE)
                {
                    Console.WriteLine("service in use!");
                }
                else if (statusMsg.status == PRSMessage.Status.ALL_PORTS_BUSY)
                {
                    Console.WriteLine("all ports busy");
                }

                // send KEEP_ALIVE
                PRSCommunicator.SendMessage(clientSocket, endPt, PRSMessage.CreateKEEP_ALIVE(serviceName, allocatedPort));

                // check status
                statusMsg = PRSCommunicator.ReceiveMessage(clientSocket, ref remoteEP);
                if (statusMsg.status == PRSMessage.Status.SUCCESS)
                {
                    Console.WriteLine("success!! yay!");
                }

                // send CLOSE_PORT

                // check status

                // send STOP
                PRSCommunicator.SendMessage(clientSocket, endPt, PRSMessage.CreateSTOP());
            }
            catch (Exception ex)
            {
                Console.WriteLine("Exception when receiving..." + ex.Message);
            }

            // close the socket and quit
            Console.WriteLine("Closing down");
            clientSocket.Close();
            Console.WriteLine("Closed!");

            Console.ReadKey();
        }
Exemplo n.º 30
0
        static void Main(string[] args)
        {
            // defaults
            ushort SERVER_PORT          = 30000;
            ushort STARTING_CLIENT_PORT = 40000;
            ushort ENDING_CLIENT_PORT   = 40099;
            int    KEEP_ALIVE_TIMEOUT   = 10;

            try
            {
                // process command options
                // -p < service port >
                // -s < starting client port number >
                // -e < ending client port number >
                // -t < keep alive time in seconds >
                for (int i = 0; i < args.Length; i++)
                {
                    switch (args[i])
                    {
                    case "-p":
                        SERVER_PORT = Convert.ToUInt16(args[++i]);
                        break;

                    case "-s":
                        STARTING_CLIENT_PORT = Convert.ToUInt16(args[++i]);
                        break;

                    case "-e":
                        ENDING_CLIENT_PORT = Convert.ToUInt16(args[++i]);
                        break;

                    case "-t":
                        KEEP_ALIVE_TIMEOUT = Convert.ToInt16(args[++i]);
                        break;
                    }
                }

                if (STARTING_CLIENT_PORT <= SERVER_PORT || STARTING_CLIENT_PORT >= ENDING_CLIENT_PORT)
                {
                    throw new Exception("Invalid range: -p must be outside of -s to -e range and -e must be larger then -s");
                }
            }
            catch (Exception ex)
            {
                Console.WriteLine("Invalid Command line Arguments");
                Console.WriteLine(ex);
                Usage();
            }


            // initialize the PRS server
            PRS prs = new PRS(STARTING_CLIENT_PORT, ENDING_CLIENT_PORT, KEEP_ALIVE_TIMEOUT);

            // create the socket for receiving messages at the server
            Socket listeningSocket = new Socket(SocketType.Dgram, ProtocolType.Udp);

            // bind the listening socket to the PRS server port
            listeningSocket.Bind(new IPEndPoint(IPAddress.Any, SERVER_PORT));

            // Process client messages

            while (!prs.Stopped)
            {
                EndPoint clientEndPoint = null;
                try
                {
                    // receive a message from a client
                    clientEndPoint = new IPEndPoint(IPAddress.Any, 0);
                    PRSMessage msg = PRSMessage.ReceiveMessage(listeningSocket, ref clientEndPoint);

                    // let the PRS handle the message
                    PRSMessage responMessage = prs.HandleMessage(msg);

                    // send response message back to client
                    responMessage.SendMessage(listeningSocket, clientEndPoint);
                }
                catch (Exception ex)
                {
                    // attempt to send a UNDEFINED_ERROR response to the client, if we know who that was
                    if (clientEndPoint != null)
                    {
                        PRSMessage errorMessage = new PRSMessage(PRSMessage.MESSAGE_TYPE.RESPONSE, "", 0, PRSMessage.STATUS.UNDEFINED_ERROR);
                    }
                }
            }

            // close the listening socket
            listeningSocket.Close();

            // wait for a keypress from the user before closing the console window
            Console.WriteLine("Press Enter to exit");
            Console.ReadKey();
        }