Use of C # Httpserver

Source: Internet
Author: User

In many cases, the applications we write need to provide an informational description or a sign function, hoping to use Httpserver to publish a simple website function, but do not want to rack a bloated HTTP server function,

At this point, the Httpserver functionality provided by the standard framework may be our choice.

The introduction of a using System.Net;

Two-start service

1   Public classServerhelper2     {3HttpListener HttpListener =NewHttpListener ();4          Public voidSetup (intport=8080)5         {            6Httplistener.authenticationschemes =authenticationschemes.anonymous;7HTTPLISTENER.PREFIXES.ADD (string. Format ("http://*:{0}/", port)); /if sent to port 8080 is not processed, it is all accepted here, + is all received8 Httplistener.start ();//Open service9 Ten Receive ();//asynchronously receives a request One         } A  -         Private voidReceive () -         { theHttplistener.begingetcontext (NewAsyncCallback (EndReceive),NULL); -         } -  -         voidEndReceive (IAsyncResult ar) +         { -             varContext =httplistener.endgetcontext (AR); + Dispather (context);//Parse Request A Receive (); at         } -  - Requesthelper Requesthelper; - Responsehelper Responsehelper; -         voidDispather (httplistenercontext context) -         { inHttpListenerRequest request=context. Request; -Httplistenerresponse response =context. Response; toRequesthelper =NewRequesthelper (request); +Responsehelper =NewResponsehelper (response); -Requesthelper.dispatchresources (fs = { the responsehelper.writetoclient (fs);//respond to the corresponding request *             }); $         }Panax Notoginseng}

Three-resolution request

1  Public classRequesthelper2     {3         Privatehttplistenerrequest request;4          PublicRequesthelper (httplistenerrequest request)5         {6              This. Request =request;7         }8          PublicStream Requeststream {Get;Set; }9          Public voidExtracheader ()Ten         { Onerequeststream=request. InputStream; A         } -  -          Public Delegate voidExecutingdispatch (FileStream FS); the          Public voiddispatchresources (executingdispatch action) -         { -             varRAWURL =request. The rawurl;//resource is placed by default in the Wwwroot file of the executing program, and the default document is Index.html -             stringFilePath =string. Format (@"{0}/wwwroot{1}", Environment.currentdirectory, RAWURL);//here corresponds to request other types of resources, slices, texts, etc. +             if(rawurl.length==1) -FilePath =string. Format (@"{0}/wwwroot/index.html", environment.currentdirectory);//default access to files +             Try { A             if(File.exists (filePath)) at             { -FileStream fs =NewFileStream (FilePath, FileMode.Open, fileaccess.readwrite); -                  -Action?. Invoke (FS); -                  -             } in             } -             Catch{return; } to         } +          Public voidResponsequerys () -         { the             varQuerys =request. QueryString; *             foreach(stringKeyinchQuerys. AllKeys) $             {Panax Notoginseng Varityquerys (Key,querys[key]); -             } the         } +  A         Private voidVarityquerys (stringKeystringvalue) the         { +             Switch(Key) -             { $                  Case "pic":P ictures (value); Break; $                  Case "text": texts (value); Break; -                 default:D efaults (value); Break; -             } the         } - Wuyi         Private voidPictures (stringID) the         { -  Wu         } -  About         Private voidTexts (stringID) $         { -  -         } -  A         Private voidDefaults (stringID) +         { the  -         } $  the}

Four response requests

 Public classResponsehelper {Privatehttplistenerresponse response;  PublicResponsehelper (httplistenerresponse response) { This. Response =response; OutputStream=Response.                   OutputStream; }         PublicStream OutputStream {Get;Set; }  Public classFileObject { PublicFileStream FS;  Public byte[] buffer; }         Public voidwritetoclient (FileStream FS) {response. StatusCode= $; byte[] buffer =New byte[1024x768]; FileObject obj=NewFileObject () {fs = FS, buffer =buffer}; Fs. BeginRead (Buffer,0, buffer. Length,NewAsyncCallback (EndWrite), obj); }               voidEndWrite (IAsyncResult ar) {varobj = ar. AsyncState asFileObject; varnum=obj.fs.EndRead (AR); Outputstream.write (Obj.buffer,0, num); if(Num <1) {
Obj.fs.Close (); Close file stream
Outputstream.close ();//Turn off the output stream, and if you do not close, the browser will be waiting for the state
           return;
} obj.fs.BeginRead (Obj.buffer,0, Obj.buffer.Length,NewAsyncCallback (EndWrite), obj); } }

Test results:

Prepare the index.html, which contains pictures and plain html

Resource directory:

Browser for access testing:

Summarize:

This article is just a simple test of httpserver, a simple request and response to the comb, for the need for complex browser functions, it is necessary to study the work of other browsers in detail

Use of C # Httpserver

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.