. NET to implement simple HTTP service _ Practical skills through HttpListener

Source: Internet
Author: User
Tags json message queue

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 like 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 the URI prefix that requires listening

3. Start listening for requests from clients

4. Handling HTTP requests from clients

5. Turn off HTTP listeners

For example: we want to implement a simple HTTP service, download the files, or do some other things, such as to send mail, use HttpListener listening, process mail queues, and avoid synchronization on the site waiting. And get 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 logical processing///</summary> public class Httpprovider { private static HttpListener httpfiledownload; File download processing request monitoring private static HttpListener httotherrequest; Other Super Request listening///<summary>///open HttpListener listening///</summary> public static void Init () {Httpfil Edownload = new HttpListener (); Create a Listener instance httpFiledownload.Prefixes.Add ("http://10.0.0.217:20009/FileManageApi/Download/");
   Add Listener address note with/end. Httpfiledownload.start ();
   Allow this listener address to accept incoming requests. Thread threadhttpfiledownload = new Thread (new ThreadStart (gethttpfiledownload));

   Create a thread that opens to listen for the address to request Threadhttpfiledownload.start ();
   Httotherrequest = new HttpListener (); HTTOTHERREQUEST.PREFIXES.ADD ("http://10.0.0.217:20009/BehaviorApi/EmailSend/"); Add toListen to the address note is at/end. Httotherrequest.start ();
   Allow this listener address to accept incoming requests.
   Thread threadhttotherrequest = new Thread (new ThreadStart (gethttotherrequest));
  Threadhttotherrequest.start (); ///<summary>///Execute file download processing request listening behavior///</summary> public static void Gethttpfiledownload () {WHI Le (True) {HttpListenerContext RequestContext = Httpfiledownload.getcontext ();//Accept new request try {//REEC  
     Ontext RequestContext Request Object Thread subthread = new Thread (new Parameterizedthreadstart (Reecontext) =>

      {Console.WriteLine ("Perform file processing request listening behavior");
      var request = (HttpListenerContext) reecontext; var image = Httputility.urldecode (request. request.querystring["Imgname"]);
      Accept the arguments from 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 stream output. Write (buffer, 0, buffer.)  Length); Writes the byte number of the buffer cache to the current request stream to return output.
      Close ();
     }
     })); Subthread. Start (RequestContext);
      Open processing 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); Turn off the output stream and release the corresponding resource output.
     Close (); The Catch {}}}///<summary>///performs other hyper-Request listening behavior///</summary> public static void Geth 
    Ttotherrequest () {while (true) {HttpListenerContext RequestContext = Httotherrequest.getcontext ();//Accept new request try {//reecontext thread subthread = new Thread (new Parameterizedthreadsta) for incoming RequestContext request object
      RT ((Reecontext) => {Console.WriteLine ("Perform other hyper-request listening behavior");
      var request = (HttpListenerContext) reecontext; var msg = Httputility.urldecode (Request. request.querystring["behavior"]);

      Accept the parameters of the GET request;//Perform the actions you need to do here >> such as cache data reading, queue message processing, mail message queue addition, etc. 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 processing 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); Turn off the output stream and release the corresponding resource output.
     Close ();

 } Catch {}}}}}

Call Mode: Note here the launcher must be run as an administrator because the morning listening requires the port to be turned on and all need to run as an 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 results after execution are:

Here a simple HTTP service program is implemented using HttpListener in a simple control program. There are a small number of threads and asynchronous processing, such as the receipt of behavior information request can be returned to the user, so that users do not have to sync waiting, you can perform the next step, such as the implementation of the Simple mail server, the request sent to HttpListener received the request immediately returned to the queue to send mail Sending a message can cause delays and wait, so you don't have to wait.

The above is the entire content of this article, I hope to help you learn, but also hope that we support the cloud habitat community.

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.