Using HttpListener to implement a simple HTTP service 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
- Creates an HTTP listener object and initializes
- Add a URI prefix to listen on
- Start listening for requests from clients
- Handling HTTP requests from clients
- Close 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.
usingSystem;usingSystem.Collections.Generic;usingSystem.Linq;usingSystem.Net;usingSystem.Text;usingSystem.Threading;usingsystem.web;usingSystem.IO;usingNewtonsoft.json;namespacehttplistenerapp{/// <summary> ///httprequest Logic Processing/// </summary> Public classHttpprovider {Private StaticHttpListener Httpfiledownload;//file download processing request Listener Private StaticHttpListener httotherrequest;//other super-do request listening /// <summary> ///turn on HttpListener monitoring/// </summary> Public Static voidInit () {httpfiledownload=NewHttpListener ();//creating a Listener instanceHTTPFILEDOWNLOAD.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 =NewThread (NewThreadStart (gethttpfiledownload));//Create to open a thread to listen to that address requestThreadhttpfiledownload.start (); Httotherrequest=NewHttpListener (); 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 =NewThread (NewThreadStart (gethttotherrequest)); Threadhttotherrequest.start (); } /// <summary> ///perform file download processing request listener Behavior/// </summary> Public Static voidgethttpfiledownload () { while(true) {HttpListenerContext RequestContext= Httpfiledownload.getcontext ();//accept a new request Try { //Reecontext an incoming RequestContext request object for an open threadThread Subthread =NewThread (NewParameterizedthreadstart ((reecontext) ={Console.WriteLine ("perform file processing request listener Behavior"); varRequest =(HttpListenerContext) Reecontext; varImage = Httputility.urldecode (request. request.querystring["imgname"]);//accept the parameters of Get request come over; stringfilepath = AppDomain.CurrentDomain.BaseDirectory +image; if(!file.exists (filepath)) {filepath= AppDomain.CurrentDomain.BaseDirectory +"default.jpg";//download default picture } using(FileStream fs =NewFileStream (filepath, FileMode.Open, FileAccess.Read)) { byte[] buffer =New byte[FS. Length]; Fs. Read (Buffer,0, (int) fs. Length);//read the file to the bufferRequest. Response.statuscode = $; Request. RESPONSE.HEADERS.ADD ("Access-control-allow-origin","*"); Request. Response.ContentType="image/jpg"; Request. Response.contentlength64=buffer. Length; varOutput = Request. Response.outputstream;//GET Request FlowOutput. Write (Buffer,0, buffer. Length);//writes the number of bytes in the buffer to the current request stream backoutput. Close (); } })); Subthread. Start (RequestContext); //turn on processing thread processing download file } Catch(Exception ex) {Try{RequestContext.Response.StatusCode= -; 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 appropriate resourcesoutput. Close (); } Catch { } } } } /// <summary> ///perform other hyper-do request listening behavior/// </summary> Public Static voidgethttotherrequest () { while(true) {HttpListenerContext RequestContext= Httotherrequest.getcontext ();//accept a new request Try { //Reecontext an incoming RequestContext request object for an open threadThread Subthread =NewThread (NewParameterizedthreadstart ((reecontext) ={Console.WriteLine ("perform other hyper-do request listening behavior"); varRequest =(HttpListenerContext) Reecontext; varmsg = Httputility.urldecode (Request. request.querystring["Behavior"]);//accept the parameters of Get request come over;//do what you need to do here >> such as what cache data reads, queue message processing, mail message queue additions, and so on. request. Response.statuscode= $; 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; varOutput =request. Response.outputstream; Output. Write (Buffer,0, buffer. Length); Output. Close (); })); Subthread. Start (RequestContext); //turn on processing thread processing download file } Catch(Exception ex) {Try{RequestContext.Response.StatusCode= -; 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 appropriate resourcesoutput. 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 { staticvoid 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. Wait a minute
Implement simple HTTP services with HttpListener