Saturday, March 21, 2015

Simple Server and Client Application


Simple Server in Console
using System.Threading.Tasks;
using System.Net;//we add this using system
using System.Net.Sockets;//we add this using system



namespace SimpleApplication_SimpleServer
{
    class Program
    {
        //rec21
        //the idea is to create two programs that do not communicate each other....we create a socket.
        //A server application is defined by its ipaddress and its port number
        //how to get the ip address?? the same as we did yesterday....the port number you give it

        const int port = 9000; // you give the port number

        static void Main(string[] args)
        {
            //first we need to create a socket..we do it in try catch.....what is a socket?? allows you to communicate
            Socket server = null;
            try
            {
                //1. create a socket object
                //READ THIS : https://msdn.microsoft.com/en-us/library/system.net.sockets.socket.accept(v=vs.110).aspx

                server = new Socket(AddressFamily.InterNetwork, //what is this?// READ THIS:https://msdn.microsoft.com/en-us/library/system.net.ipaddress.addressfamily%28v=vs.110%29.aspx
                                    SocketType.Stream,//what does this do?
                                    ProtocolType.Tcp);// ''         ''?
                //2. Get the IPAddress of this local computer and bind(set) it to the socket
                IPAddress[] ipaddresses = Dns.GetHostAddresses(Dns.GetHostName());//what is Ipadddress?
                //IPAddress ipaddress = ipaddresses[1]; (without using method)
                IPAddress ipaddress = GetValidv4IpAddress(ipaddresses);
             
                //READ THIS:https://msdn.microsoft.com/en-us/library/system.net.ipendpoint%28v=vs.110%29.aspx
                IPEndPoint endP = new IPEndPoint(ipaddress, port);
                server.Bind(endP);
             
           
                //display that server is ready
                Console.WriteLine("\nServer is ready/listening at ipaddresses: {0} and port: {1}", ipaddress, port);
                //3.set server in the Listen mode..
                server.Listen(12); //The listen method runs in an internal task that listens for client request and queue them in a  backlog queue,

                //4. accept Client 
                //accepting the client means gets the next waiting client from the backlog queue
                while (true)
                {
                    //get the next waiting client
                    Socket client = server.Accept();//get a reference to the client socket....log /display cliente information...process cliente request
                    DisplayClientInfo(client);
                    //process client request.
                    Task task = Task.Factory.StartNew(() => ProcessClient(client));
                }
            }
            catch (SocketException se)
            {
                string sckException = se.ToString();
            }
         
        }
        static void DisplayClientInfo(Socket client)
        {
            //get the ip address and the port of the client
            IPEndPoint clientEndP = (IPEndPoint)client.RemoteEndPoint;
            IPAddress clientIpaddress = clientEndP.Address;
            int clientPort = clientEndP.Port;
            Console.WriteLine("Client Request from:{0}: {1}", clientIpaddress, clientPort);
        }

        static void ProcessClient(Socket client)
        {
            //Expectation:
            //Add number1 number2
            //Sub number1 number2
            //Mul number1 number2
            //Div number1 number2

            //receive the client request
            byte[] data = new byte[256];
            int byteReceived = client.Receive(data);
            //convert the received byte to a string
            string request = Encoding.UTF8.GetString(data, 0, byteReceived);

            //process it
            string response = ProcessRequest(request);

            //send response
            byte[] buffer = Encoding.UTF8.GetBytes(response);
            client.Send(buffer);
        }
        //process request
        static private string ProcessRequest(string request)
        {
            string response = String.Empty;
            //split the request by space
            string[] words = request.Split(' ');

            if (words.Length != 3)
            {
                response = "Request not in correct format";
                return  response;
            }

            //Convert input to double
            double v1, v2;
            double.TryParse(words[1], out v1);
            double.TryParse(words[2], out v2);

            switch (words[0].ToLower())
            {
                case "add":
                    double result = v1 + v2;
                    response = result.ToString();
                    break;
                case "sub":
                     result = v1 - v2;
                    response = result.ToString();
                    break;
                case "mul":
                    result = v1 * v2;
                    response = result.ToString();
                    break;
                case "div":
                    if (v2 != 0)
                    {
                        result = v1 / v2;
                        response = result.ToString();
                    }
                    else
                    {
                        response = "Divide by zero error";
                    }
                    break;
            }
            return response;
        }

        //Method to return a valid ip v4 address
        static IPAddress GetValidv4IpAddress(IPAddress[] ipaddresses)
        {
            IPAddress ipaddress;

            foreach (IPAddress address in ipaddresses)
            {
                if (IPAddress.TryParse(address.ToString(), out ipaddress)) //Is it an ipv4
                {
                    if (address.AddressFamily == AddressFamily.InterNetwork)
                    {
                        return address;
                    }
                }
            }
            return null; //If no ip v4 exists
        }
    }
}
//Lab Assignment:
//Either new project or add to this one
//Allow user to compute square root, power (ex: value raised to the power of exponent)
//and the log of a number. (The client should not change, but the server 
//processRequest needs to.)

////msdn.microsoft.com/en-us/library/system.net.sockets.socketasynceventargs(v=vs.110).aspx

//==========================================================
using System.Windows.Forms;
using System.Net; //Added
using System.Net.Sockets; //Added
using System.Threading;
//============ZAU==========

namespace SimpleClient
{
    public partial class Form1 : Form
    {
        public Form1()
        {
            InitializeComponent();
        }

        private async void btnSendRequest_Click(object sender, EventArgs e)
        {
            //Create a Socket
            Socket client = null;
            try
            {
                //1. Create socket
                client = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp);

                //2. Create the server endPoint
                //Get IP address of the server
                IPAddress[] ipaddressess = await Dns.GetHostAddressesAsync(txtDomainName.Text);
                        //Create EndPoint of the server

                int port = int.Parse(txtPortNumber.Text);
                //IPAddress ipaddress = GetValidv4PAddress(ipaddress);
                IPAddress ipaddress = GetValidv4PAddress(ipaddressess);
                EndPoint serverEndP = new IPEndPoint(ipaddress, port);

                //3. Connect to the server
                client.Connect(serverEndP);

                //4. Send a request to the server
                //://msdn.microsoft.com/en-us/library/system.net.sockets.socket.send(v=vs.110).aspx
                string request = txtServiceRequested.Text;
                //convert to byte array
                byte[] buffer = Encoding.UTF8.GetBytes(request);

                client.Send(buffer);

                //5. get a response from the server ----- Receive Code
                //create a byte array  
                byte[] data = new byte[256];
                int byteReceived = client.Receive(data);
                //convert the received byte to a string
                string response = Encoding.UTF8.GetString(data, 0, byteReceived);
             
                //Display it
                richTextBox1.Text = response;
            }
            catch (FormatException fe)
            {
                MessageBox.Show(fe.Message);
            }
            catch (SocketException se)
            {
                MessageBox.Show(se.Message);
            }
            finally
            {
                if (client != null)
                {
                    client.Shutdown(SocketShutdown.Both);
                    client.Close();
                }
            }
        }

        //button for the async method
        private void btnApplyAsyncMethod_Click(object sender, EventArgs e)
        {
            //Apply Async to the send and receive in the client code

        }

        //method to return a valid ip V4 address
        private IPAddress GetValidv4PAddress(IPAddress[] ipaddresses)
        {
            IPAddress ipaddress;
            foreach (IPAddress address in ipaddresses)
            {
                if (IPAddress.TryParse(address.ToString(), out ipaddress)) // is it and ipv4 ...what is this?
                {

                    if (address.AddressFamily == AddressFamily.InterNetwork)
                    {
                        return address;
                    }
                }
            }
            return null; //if no ip v4 exists
        }
    }
}

No comments:

Post a Comment