. NET implementation of simple HTTP service via HttpListener

Source: Internet
Author: User
The HttpListener provides a simple, programmatically controlled HTTP protocol listener. Using it makes it easy to provide some HTTP services without having to start a large service program such as IIS. The process of using HttpListener is simple: it is mainly divided into the following steps

1. Create an HTTP listener object and initialize

2. Add a URI prefix to listen on

3. Start listening for requests from clients

4. Handling HTTP requests from clients

5. Turn off the HTTP listener

For example: we want to implement a simple HTTP service, download the file, or do some other things, such as sending mail, using HttpListener listening, processing the message queue, avoiding the synchronization wait on the website. And getting some cached data, and so on.

Using system;using system.collections.generic;using system.linq;using system.net;using System.Text;using System.threading;using system.web;using system.io;using newtonsoft.json;namespace HttpListenerApp{//<summary >//HttpRequest logic processing///</summary> public class Httpprovider {private static HttpListener httpfiledownload; /File download processing request listener private static HttpListener httotherrequest; Other super-do request listening///<summary>///HttpListener monitoring///</summary> public static void Init () {Httpfiledownlo AD = new HttpListener (); Create a Listener instance httpFiledownload.Prefixes.Add ("http://10.0.0.217:20009/FileManageApi/Download/");   Add a listener address note to the/end. Httpfiledownload.start ();   Allows the listener address to accept incoming requests. Thread threadhttpfiledownload = new Thread (new ThreadStart (gethttpfiledownload));   Create to open a thread to listen to the address of the request Threadhttpfiledownload.start ();   Httotherrequest = new HttpListener (); HTTOTHERREQUEST.PREFIXES.ADD ("http://10.0.0.217:20009/BehaviorApi/EmailSend/");   Add a listener address note to the/end. Httotherrequest.stArt ();   Allows the listener address to accept incoming requests.   Thread threadhttotherrequest = new Thread (new ThreadStart (gethttotherrequest));  Threadhttotherrequest.start (); }///<summary>///Perform file download processing request listener behavior////</summary> public static void Gethttpfiledownload () {while (Tru e) {HttpListenerContext requestcontext = Httpfiledownload.getcontext ();//Accept new request try {//reecontext to open thread Incoming RequestContext Request object Thread subthread = new Thread (new Parameterizedthreadstart (reecontext) = {Cons Ole.      WriteLine ("Perform file processing request listening behavior");      var request = (HttpListenerContext) reecontext; var image = Httputility.urldecode (request. request.querystring["Imgname"]);      Accept the arguments for the GET request; string filepath = AppDomain.CurrentDomain.BaseDirectory + image; if (!  File.exists (filepath)) {filepath = AppDomain.CurrentDomain.BaseDirectory + "default.jpg"; Download default picture} using (FileStream fs = new FileStream (filepath, FileMode.Open, FileAccess.Read)) {byte[] Buffer =New Byte[fs.       Length]; Fs. Read (buffer, 0, (int) fs. Length); Read the file to the cache request.       Response.statuscode = 200; Request.       RESPONSE.HEADERS.ADD ("Access-control-allow-origin", "*"); Request.        Response.ContentType = "Image/jpg"; Request. response.contentlength64 = buffer.       Length; var output = Request. Response.outputstream; Gets the request flow output. Write (buffer, 0, buffer.  Length); Writes the number of bytes in the buffer to the current request stream to return output.      Close ();     }     })); Subthread. Start (RequestContext);      Open process thread processing download file} catch (Exception ex) {try {requestContext.Response.StatusCode = 500;      RequestContext.Response.ContentType = "Application/text";      requestContext.Response.ContentEncoding = Encoding.UTF8;      byte[] buffer = System.Text.Encoding.UTF8.GetBytes ("System Error");      Output the appropriate information to the client. requestContext.Response.ContentLength64 = buffer.      Length;      System.IO.Stream output = RequestContext.Response.OutputStream; Output. Write (buffer, 0, buffer.    Length);  Closes the output stream, releasing the corresponding resource output.     Close (); } Catch {}}}}//<summary>//Perform other hyper-do request listening behavior////</summary> public static void Gethttotherre     Quest () {while (true) {HttpListenerContext RequestContext = Httotherrequest.getcontext ();//Accept new request try { Reecontext the RequestContext Request object Thread subthread = new Thread (New Parameterizedthreadstart ((reecontext) =      > {Console.WriteLine ("Perform other super-do request listening behavior");      var request = (HttpListenerContext) reecontext; var msg = Httputility.urldecode (Request. request.querystring["behavior"]);      Accept the arguments for GET requests;//Perform the actions you need to do here >> such as what cache data reads, queue message processing, mail message queue additions, and so on. Request.      Response.statuscode = 200; Request.      RESPONSE.HEADERS.ADD ("Access-control-allow-origin", "*"); Request.      Response.ContentType = "Application/json";      requestContext.Response.ContentEncoding = Encoding.UTF8; byte[] buffer = System.Text.Encoding.UTF8.GetBytes (Jsonconvert.serializeobject (New {success = true, bEhavior = msg}); Request. response.contentlength64 = buffer.      Length; var output = Request.      Response.outputstream; Output. Write (buffer, 0, buffer.      Length); Output.     Close ();     })); Subthread. Start (RequestContext);      Open process thread processing download file} catch (Exception ex) {try {requestContext.Response.StatusCode = 500;      RequestContext.Response.ContentType = "Application/text";      requestContext.Response.ContentEncoding = Encoding.UTF8;      byte[] buffer = System.Text.Encoding.UTF8.GetBytes ("System Error");      Output the appropriate information to the client. requestContext.Response.ContentLength64 = buffer.      Length;      System.IO.Stream output = RequestContext.Response.OutputStream; Output. Write (buffer, 0, buffer.      Length); Closes the output stream, releasing the corresponding resource output.     Close (); } Catch {}}}}}



Call Method: Note Here the startup program must run as an administrator, because the morning listening needs to open the port, all need to run as administrator.

Using system;using system.collections.generic;using system.linq;using system.text;namespace HttpListenerApp{class program {  static void Main (string[] args)  {   //Open Request Listener   httpprovider.init ();  }}}



The result after execution is:



Here, a simple control program is used to implement a simple HTTP service using HttpListener. There are a small number of threads and asynchronous processing, such as the receipt of behavior information requests can be returned to the user, so that users do not have to wait, you can do the next step, such as the implementation of the Simple mail server, send the request to HttpListener received the request immediately return, to the queue to send the message. There is a delay waiting for the message to be sent, so there is no waiting.

The above is. NET through the HttpListener implementation of the simple HTTP service content, more relevant content please pay attention to topic.alibabacloud.com (www.php.cn)!

  • Related Article

    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.