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.

1 HttpListener listener = newHttpListener();

  

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:
        1 listener.Prefixes.Add("http://127.0.0.1:8080/")    //必须以‘/‘结尾
        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:

1 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.

12 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:

Using system;using system.collections.generic;using system.linq;using system.text;using System.Net;using System.IO;        Namespace webconsole{class Program {static HttpListener ssocket;            static void Main (string[] args) {ssocket = new HttpListener ();            SSOCKET.PREFIXES.ADD ("http://127.0.0.1:8080/");            Ssocket.start ();            Ssocket.begingetcontext (New AsyncCallback (Getcontextcallback), ssocket);            Console.WriteLine ("Started monitoring, Access http://127.0.0.1:8080/");        Console.readkey (); } static void Getcontextcallback (IAsyncResult ar) {try {Ssock ET = ar.                AsyncState as HttpListener;                HttpListenerContext context = Ssocket.endgetcontext (AR);                Listen again for request Ssocket.begingetcontext (new AsyncCallback (Getcontextcallback), ssocket); Process Request String A = Request (context.                Request);       Output request         Response (context.            Response, a); } catch {}}///<summary>//Process input parameters////</summary>//&LT;PA Ram Name= "Request" ></param>///<returns></returns> static string request (Httplistenerr            Equest request) {String temp = "Welcome to linezero!"; if (Request. Httpmethod.tolower (). Equals ("get")) {//get requests processing if (!string. IsNullOrEmpty (Request. querystring["Linezero"]) temp = Request.            querystring["Linezero"]; } else if (request. Httpmethod.tolower (). Equals ("POST")) {//This is the default comment off//if (!request) that must be passed at the time of the POST request.                Hasentitybody)//{//Temp = "Please pass in Parameters";                return temp; }//post Requests processing Stream Sourcestream = Request.                InputStream; Byte[] CurrenTchunk = Readlineasbytes (Sourcestream); There are whitespace characters in the fetch data that need to be removed, and the output is the parameter string for the POST request such as: Username=linezero temp = Encoding.Default.GetString (currentchunk).            Replace ("", "");        } return temp;            } static byte[] Readlineasbytes (Stream sourcestream) {var resultstream = new MemoryStream ();                while (true) {int data = Sourcestream.readbyte ();                Resultstream.writebyte ((byte) data);            if (data <=) break;            } resultstream.position = 0;            byte[] databytes = new Byte[resultstream.length];            Resultstream.read (databytes, 0, databytes.length);        return databytes; }///<summary>/////</summary>//<param name= "Response" >response Elephant </param>//<param name= "responsestring" > Output value </param>//<param name= "contenttype" > Output type default to json</param> static void Response (Httplistenerresponse Response, String Responsestri Ng, String contenttype = "Application/json") {response.            StatusCode = 200; 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); Closes the output stream, releasing the corresponding resource output.        Close (); }    }}

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

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.