) Use httplistener to implement simple Web Servers

Source: Internet
Author: User

Address: http://www.cnblogs.com/wlitsoft/archive/2012/04/25/2469524.html

 

I don't know if you haven't read the previous blog. The previous article will use the underlying socket to implementSimple Web ServerIsn't it complicated? Don't be afraid that this blog will show you a new implementation method, that is, using httplistener.


To further simplify the HTTP listener ,. NET provides the httplistener class for us. net ). net encapsulates a series of HTTP protocol processing work in this class.

First, let's take a look at the definition in msdn:

Note: This class is added in. NET Framework 2.0.

Provides a simple HTTP listener that can be programmed. This class cannot be inherited.

Usage:

Public Sealed ClassHttplistener: idisposable
Note: This class can only be used in Windows XP or Windows Server 2003 or later, because this class must use HTTP. sys system components to complete the work.
Therefore, you should determine whether the class is supported before use.

//Check whether the system supportsIf(!Httplistener. issupported ){Throw NewSystem. invalidoperationexception ("Httplistener must be Windows XP SP2 or server 2003 or later!");}
 
 

The following lists some attribute methods used in this case.
1.Httplistener. prefixes
Obtain the prefix of the URI (unified resource identifier) processed by the httplistener object.

//  Note that the prefix must end with a forward slash (/).  String [] Prefixes = New   String [] { "  Http: // localhost: 8080/  "  };  //  Create a listener. Httplistener listener = New  Httplistener ();  // Adds the prefix of the listener.  Foreach ( String S In  Prefixes) {listener. prefixes. Add (s );} 

2.Start ()Method allows this instance to accept incoming requests. Start listening

3.Stop ()Method to close the httplistener object after processing all the requests currently queued

4.Getcontext ()The method returned when the incoming request is received is the same as the socket implementation server in the previous article.
There is an accept () method. Both of them are almost waiting for incoming requests.
The getcontext () method also blocks the thread. When the client requests arrive, an httplistenercontext object is returned to process the requests sent by the client.

4.1 get the httplistenerrequest object that represents the client resource.

4.1.1 accepttype: Obtain the MIME type received by the client.
4.1.2
Userages gets language information.

4.1.3 useragent
Obtain the user agent provided by the client.

4.1.4 Headers
Get the set of header names/value pairs sent in the request ---> get the properties not provided by the httplistenerrequest class.

4.2
Response this property gets the httplistenerresponse object, which will be sent to the client in response to the client's request.

4.2.1 contextlength64 obtains or sets the number of bytes of body data contained in the response.

4.2.2 contexttype: obtain or set the MIME type of the returned content.

PassStream ModeSend the content of the Response Message to the client browser.

The following is the source code of this article:

            //  Check whether the system supports              If (! Httplistener. issupported ){  Throw   New  System. invalidoperationexception (  "  Httplistener must be Windows XP SP2 or server 2003 or later!  "  );}  //  Note that the prefix must end with a forward slash (/).             String [] Prefixes = New   String [] { "  Http: // localhost: 49152/  "  };  //  Create a listener. Httplistener listener = New  Httplistener ();  //  Adds the prefix of the listener.             Foreach ( String S In  Prefixes) {listener. prefixes. Add (s );}  //  Start listening  Listener. Start (); console. writeline (  "  Listening...  "  );  While ( True ){  //  Note: The getcontext method will block the thread until the request arrives. Httplistenercontext context = Listener. getcontext ();  //  GET request object Httplistenerrequest request = Context. Request; console. writeline (  "  {0} {1} HTTP/1.1  "  , Request. httpmethod, request. rawurl); console. writeline ( "  Accept: {0}  " , String . Join ( "  ,  "  , Request. accepttypes); console. writeline (  "  Accept-language: {0}  "  ,  String . Join ( " ,  "  , Request. userpolicages); console. writeline (  "  User-Agent: {0}  "  , Request. useragent); console. writeline (  "  Accept-encoding: {0}  " , Request. headers [ "  Accept-Encoding  " ]); Console. writeline (  "  Connection: {0}  "  , Request. keepalive ? "  Keep-alive  " : "  Close  "  ); Console. writeline (  "  HOST: {0} "  , Request. userhostname); console. writeline (  "  Pragma: {0}  " , Request. headers [ "  Pragma  "  ]);  //  Get Response object Httplistenerresponse response = Context. response;  // Construct response content                  String  Responsestring = @"  <HTML>   "  ;  //  Set the response header content, length, encoding  Response. contentlength64 =System. Text. encoding. utf8.getbytecount (responsestring); response. contenttype = "  Text/html; charsets = UTF-8  "  ;  //  Output Response content System. Io. stream output = Response. outputstream; system. Io. streamwriter writer = New  System. Io. streamwriter (output); writer. Write (responsestring ); //  The output stream must be disabled.  Writer. Close ();  If  (Console. keyavailable)  Break  ;}  //  Disable the server Listener. Stop ();

Check the packets through httpwatch.

Does the packet have the same attributes as those specified in the source code?
(* ^__ ^ *) Xi ...... This article is here (^_^ )/~~ Bye bye

crazy!
what's important is that the running result is the point I listed above.

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.