Implement a simple Web server yourself, support get post requests

Source: Internet
Author: User

The last thing that comes to mind is the need to implement a Web server to process the request, and then send the message to another program. The result is then returned to the processing and rendered.

Now I'm going to share a little bit about how it's achieved.

The HttpListener class provided by. NET implements the processing of the HTTP protocol and implements a simple Web server.

Note: This class is new in the. NET Framework version 2.0. Therefore, support for the. NET Framework version 2.0 or later is supported. This class is available only on computers that are running Windows XP SP2 or the Windows Server 2003 operating system.

Reference namespaces: Using System.Net;

The general steps for using the HTTP service are:

    1. Creates an HTTP listener object and initializes
    2. Start listening for requests from clients
    3. Handling HTTP requests from clients
    4. Close the HTTP listener

Create an HTTP Listener object

Creating an HTTP Listener object requires just a new HttpListener object.

HttpListener listener = new HttpListener ();

  

Initialization takes the following two steps

      1. To add a range of URLs that you need to listen to in listener.prefixes, you can do this through the following functions:
        Listener. Prefixes.add ("http://127.0.0.1:8080/")    //must end with '/'
        Multiple words can be added with loops.
      2. Call listener. Start () implements the binding of the port and begins to listen for the client's requirements.

Listening for requests from clients

There are 2 ways to listen for HTTP requests, and the simplest way to get HttpListenerContext is as follows:

HttpListenerContext context = listener. GetContext ();

This method blocks the calling function until a client request is received, and if you want to increase the response speed, you can use the Async method listener. Begingetcontext () to achieve the acquisition of the HttpListenerContext object.

I'm using the asynchronous way to get the HttpListenerContext object.

Handling HTTP requests from clients

After getting httplistenercontext, you can get the object that represents the client request through the request property, and through the response property, the object that represents the response HttpListener will send to the client.

HttpListenerRequest request = context. Request; Httplistenerresponse response = context. Response;

Close the HTTP listener

by calling listener. The Stop () function closes the listener and frees the associated resource

Implementing get POST Request processing

Get requests are straightforward and go directly through request. querystring["Linezero"]; QueryString can be implemented to obtain parameters.

Post request because HttpListener does not provide implementation, need to do their own processing. The method is posted in the relevant code below.

Related code:

usingSystem;usingSystem.Collections.Generic;usingSystem.Linq;usingSystem.Text;usingSystem.Net;usingSystem.IO;namespacewebconsole{classProgram {StaticHttpListener Ssocket; Static voidMain (string[] args) {Ssocket=NewHttpListener (); SSOCKET.PREFIXES.ADD ("http://127.0.0.1:8080/");            Ssocket.start (); Ssocket.begingetcontext (NewAsyncCallback (Getcontextcallback), ssocket); Console.WriteLine ("monitoring started, access http://127.0.0.1:8080/");        Console.readkey (); }                Static voidgetcontextcallback (IAsyncResult ar) {Try{Ssocket= Ar. AsyncState asHttpListener; HttpListenerContext Context=ssocket.endgetcontext (AR); //Listen again for requestsSsocket.begingetcontext (NewAsyncCallback (Getcontextcallback), ssocket); //Processing Requests                stringA =Request (context.                Request); //Output RequestResponse (context.            Response, a); }            Catch { }        }        /// <summary>        ///working with input parameters/// </summary>        /// <param name= "Request" ></param>        /// <returns></returns>        Static stringrequest (HttpListenerRequest request) {stringtemp ="Welcome to Linezero!"; if(Request. Httpmethod.tolower (). Equals ("Get"))             {                //GET request Processing                if(!string. IsNullOrEmpty (Request. querystring["Linezero"]) Temp= Request. querystring["Linezero"]; }            Else if(Request. Httpmethod.tolower (). Equals ("Post"))             {                //This is the default comment that must be passed at the time of the POST request//if (!request. Hasentitybody)//{                //temp = "Please pass in Parameters"; //return temp; //}                //POST request ProcessingStream Sourcestream =request.                InputStream; byte[] Currentchunk =readlineasbytes (Sourcestream); //there are whitespace characters to be removed from the data, and the output is the parameter string for the POST request such as: Username=linezerotemp = Encoding.Default.GetString (currentchunk). Replace ("",""); }                        returntemp; }        Static byte[] readlineasbytes (Stream sourcestream) {varResultstream =NewMemoryStream ();  while(true)            {                intdata =Sourcestream.readbyte (); Resultstream.writebyte ((byte) data); if(Data <=Ten)                     Break; } resultstream.position=0; byte[] Databytes =New byte[Resultstream.length]; Resultstream.read (Databytes,0, databytes.length); returndatabytes; }        /// <summary>        ///Output Method/// </summary>        /// <param name= "Response" >Response Object</param>        /// <param name= "responsestring" >Output Value</param>        /// <param name= "contenttype" >output type defaults to JSON</param>        Static voidResponse (Httplistenerresponse Response,stringResponsestring,stringContentType ="Application/json") {Response. StatusCode= $; Response. ContentType=contenttype; Response. ContentEncoding=Encoding.UTF8; byte[] buffer =System.Text.Encoding.UTF8.GetBytes (responsestring); //output the appropriate information to the client.Response. ContentLength64 =buffer.            Length; System.IO.Stream Output=Response.            OutputStream; Output. Write (Buffer,0, buffer.            Length); //turn off the output stream and release the appropriate resourcesoutput.        Close (); }    }}
View Code

Finally start the program, in the address bar input http://127.0.0.1:8080 can be accessed.

If you think this article is helpful to you, please click " recommend ", thank you.

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.