Share via


Responding to a Http Message from a Console Application

Question

Tuesday, May 27, 2014 4:26 AM

Hi all,

I want to develop a simple console Application in C# that wll handle Http Requests and sends the response back to a Browser or any other Client  that sends a Http Request to this Console Application. Currently, I am using a Socket to listen on a port for a Http Request and I don't know how to generate the Http Response for the received request. I am poting here the code of my Console Application. Could someone help me on how to construct a Http Response to a request from my console Application?

private void Handler()
        {
            bool recvRequest = true;
            string EOL = "\r\n";
            int bodylength = 0;
            string requestPayload = "";
            string requestTempLine = "";
            List<string> requestLines = new List<string>();
            byte[] requestBuffer = new byte[1];
            byte[] responseBuffer = new byte[1];
            requestLines.Clear();

            try
            {
                //State 0: Handle Request from Client
                while (recvRequest)
                {
                    while (this.clientSocket.Available != 0)
                    {
                        this.clientSocket.Receive(requestBuffer);
                        string fromByte = ASCIIEncoding.ASCII.GetString(requestBuffer);
                        requestPayload += fromByte;
                        requestTempLine += fromByte;

                        if (requestTempLine.EndsWith(EOL))
                        {
                            requestLines.Add(requestTempLine.Trim());
                            requestTempLine = "";
                        }

                        if (requestPayload.Contains(EOL + EOL))
                        {
                            string[] list = requestLines.ToArray();
                            string body = "";
                            foreach (string s in list)
                            {
                                if (s.Contains("Content-Length"))
                                {
                                    bodylength = Convert.ToInt32(s.Split(':')[1]);
                                    for (int i = 0; i < bodylength; i++)
                                    {
                                        this.clientSocket.Receive(requestBuffer);
                                        fromByte = ASCIIEncoding.ASCII.GetString(requestBuffer);
                                        body += fromByte;
                                    }
                                    requestPayload += body;
                                    requestLines.Add(body);

                                    AccountNo = Convert.ToInt64(body.Split('&')[0].Split('=')[1]);
                                    Amount = Convert.ToInt64(body.Split('&')[1].Split('=')[1]);
                                }
                            }
                            recvRequest = false;
                        }
                    }
                }
                Console.WriteLine("Raw Request Received...as \n {0}",requestPayload);

/*
Need to insert the code for constructing a Http Response and send back to the Client...
*/

Thanks,

K.V.N.PAVAN

All replies (3)

Tuesday, June 3, 2014 9:48 AM âś…Answered

Hi Pa1 Kumar,

To build a Http server, you need to understand Http.

http://www.w3.org/Protocols/rfc2616/rfc2616.html

If you use some tools like Fiddler or HttpWatch or something like this, you'll find that a Http response looks like this:

HTTP/1.1 200 OK
Last-Modified: Wed, 17 Oct 2007 03:01:41 GMT
Content-Type: text/html
Content-Length: 158
Date: Wed, 17 Oct 2007 03:01:59 GMT
Server: Apache-Coyote/1.1

...

It consists of four parts, the status line(HTTP/1.1 200 OK), the response header(Content-Type:text/html...), an empty line and the response body. So in your Http server, when you receive a Http request using Socket, you need to send a string content just like this. The client web browser only recogonize the strings that is formatted as Http response.

I just made an example a few days before, here's the code snippet, hope it can help you:

IPAddress localaddress = IPAddress.Loopback;
            IPEndPoint endpoint = new IPEndPoint(localaddress, 11111);
            Console.WriteLine(string.Format("Listening port:{0}",11111));
            Socket socket = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp);
            socket.Bind(endpoint);
            socket.Listen(10);

            Console.WriteLine("Waiting for http request...\r\n");
            Socket clientsocket = socket.Accept();

            Console.WriteLine("Client connected: {0}\r\n", clientsocket.RemoteEndPoint);
            byte[] buffer = new byte[1024];
            int receivelength = clientsocket.Receive(buffer, 1024, SocketFlags.None);
            string requeststring = Encoding.UTF8.GetString(buffer, 0, receivelength);

            Console.WriteLine(requeststring);

            string statusLine = "HTTP/1.1 200 OK\r\n";
            string responseHeader = "Content-Type: text/html\r\n";
            string responseBody = "<html><head><title>Hello World!</title></head><body><div>Hello World!</div></body></html>";

            clientsocket.Send(Encoding.UTF8.GetBytes(statusLine));
            clientsocket.Send(Encoding.UTF8.GetBytes(responseHeader));
            clientsocket.Send(Encoding.UTF8.GetBytes("\r\n"));
            clientsocket.Send(Encoding.UTF8.GetBytes(responseBody));

            clientsocket.Close();

            Console.ReadLine();

            socket.Close();

For all information of the response code, please check the 10th chapter of the above document:

http://www.w3.org/Protocols/rfc2616/rfc2616-sec10.html

We are trying to better understand customer views on social support experience, so your participation in this interview project would be greatly appreciated if you have time. Thanks for helping make community forums a great place.
Click HERE to participate the survey.


Wednesday, May 28, 2014 6:41 AM

Hello,

Take a look at the System.Net.WebClient class, it can be used to issue requests and handle their responses, as well as to download files:

http://www.hanselman.com/blog/HTTPPOSTsAndHTTPGETsWithWebClientAndCAndFakingAPostBack.aspx

http://msdn.microsoft.com/en-us/library/system.net.webclient(VS.90).aspx

Thanks.


Wednesday, May 28, 2014 2:23 PM

Hi Diana,

Thanks for the reply, but I atually need a server functionality where the Console Application acts as a Server and responds with a Http Response for the incoming Http Requests. I think the System.Net.WebClient class will be dealing more with Client Functionality . Do you find some other way for server functionality.

Thanks,

K.V.N.PAVAN