. NET implements simple Http services through HttpListener,. nethttplistener

Source: Internet
Author: User

. NET implements simple Http services through HttpListener,. nethttplistener

HttpListener provides a simple HTTP listener that can be controlled programmatically. It can easily provide some Http services without starting large service programs such as IIS. The process of using HttpListener is simple: mainly divided into the following steps:

1. Create an HTTP listener object and initialize it.

2. Add the URI prefix to be listened

3. Start listening for requests from the client

4. process Http requests from the client

5. Disable the HTTP listener

For example, we want to implement a simple Http service to download files or perform some other operations, such as sending emails, using HttpListener to listen and process the mail queue, avoid waiting for synchronization on the website. And get some cached data.

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; // The File Download Processing request listens to the private static HttpListener httOtherRequest; // other requests that exceed the listener // <summary> // enable the HttpListener listener /// </summary> public static void Init () {httpFiledownload = new HttpListener (); // create a listener instance httpFiledownload. prefixes. add (" http://10.0.0.217:20009/FileManageApi/Download/ "); // Add the listening address. Note that it ends. HttpFiledownload. Start (); // allows the listener address to accept incoming requests. Thread ThreadhttpFiledownload = new Thread (new ThreadStart (GethttpFiledownload); // create a Thread to listen to the address and request ThreadhttpFiledownload. start (); httOtherRequest = new HttpListener (); httOtherRequest. prefixes. add (" http://10.0.0.217:20009/BehaviorApi/EmailSend/ "); // Add the listening address. Note that it ends. HttOtherRequest. Start (); // allows the listener address to accept incoming requests. Thread ThreadhttOtherRequest = new Thread (new ThreadStart (GethttOtherRequest); ThreadhttOtherRequest. start () ;}//< summary> /// execution File Download Processing request listening behavior /// </summary> public static void GethttpFiledownload () {while (true) {HttpListenerContext requestContext = httpFiledownload. getContext (); // receives a new request. try {// reecontext is the requestContext request object Thread subthread = new Thread (new ParameterizedThreadSta Rt (reecontext) => {Console. writeLine ("execution File Processing request listening behavior"); var request = (HttpListenerContext) reecontext; var image = HttpUtility. urlDecode (request. request. queryString ["imgname"]); // parameters received by the GET request; string filepath = AppDomain. currentDomain. baseDirectory + image; if (! File. exists (filepath) {filepath = AppDomain. currentDomain. baseDirectory + "default.jpg"; // download default image} 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; // get the request stream output. write (buffer, 0, buffer. length); // write the number of bytes in the cache area to the current request stream and return the output. close () ;}}); subthread. start (requestContext); // enable the processing thread to process downloaded files} 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"); // outputs the corresponding information to the client. requestContext. response. contentLength64 = buffer. length; System. IO. stream output = requestContext. response. outputStream; output. write (buffer, 0, buffer. length); // close the output stream and release the corresponding resource output. close ();} catch {}}}/// <summary> // execute other superscript request listening behavior // </summary> public static void GethttOth ErRequest () {while (true) {HttpListenerContext requestContext = httOtherRequest. getContext (); // receive new request try {// reecontext is the requestContext request object Thread subthread = new Thread (new ParameterizedThreadStart (reecontext) ==>{ Console. writeLine ("execute other superscript request listening behaviors"); var request = (HttpListenerContext) reecontext; var msg = HttpUtility. urlDecode (request. request. queryString ["behavior"]); // receives the GET request parameters.; // Perform the operations you need here> such as cache data reading, queue message processing, and addition of mail message queues. 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); // enable the processing thread to process downloaded files} 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"); // outputs the corresponding information to the client. requestContext. response. contentLength64 = buffer. length; System. IO. stream output = requestContext. response. outputStream; output. write (buffer, 0, buffer. length); // close the output stream and release the corresponding resource output. close () ;}catch {}}}}}}

Call method: note that the startup program must run as an administrator, because the listening in the morning needs to enable the port, and all programs must run as administrators.

Using System; using System. collections. generic; using System. linq; using System. text; namespace HttpListenerApp {class Program {static void Main (string [] args) {// enable HTTP provider for request listening. init ();}}}

The execution result is:

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. For example, when a request for behavior information is received, it can be returned to the user first, so that the user can perform the next operation without waiting synchronously, and for example, the implemented Simple Mail Server, send the request to HttpListener immediately after receiving the request, and send it to the queue to send the mail. Delayed waiting occurs when sending emails, so you don't have to wait.

The above is all the content of this article. I hope it will be helpful for your learning and support for helping customers.

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.