C # implement a simple HTTP server.

Source: Internet
Author: User
The main classes used are httplistener and streamwriter.

Httplistener: Use httplistener to create a simple HTTP listener that responds to HTTP requests. In fact, httplistener only implements a simple encapsulation class on the server socket. Set the prefixes attribute to listen. For example, the listener is bound to the URL of the HTTP or HTTPS endpoint (the following code ). by default, the listener is bound to port 80 running on HTTP and port 443 of HTTPS, and can be accessed by anonymous and unauthenticated clients. You can use the prefixes attribute of the httplistener class to customize URLs and ports, and configure authentication by setting the authenticationschemes attribute.

After the httplistener is set up, run start (which actually triggers the underlying bind and listener) to process the incoming requests from the client. In httplistener, getcontext is similar to the socket's accept, which is blocked when no request is ready for processing. Getcontext returns an object httplistenercontext. The request attribute of the httplistenercontext object provides a lot of request information about the client. Response Returns An httplisterresponse object, which can be used to respond to client requests.

The Code is as follows:

Using system;

Using system. Collections. Generic;

Using system. text;

Using system. net;

Using system. net. Sockets;

Using system. IO;

Namespace consolehttpechoserver


Class Program


Static void main (string [] ARGs)


Using (httplistener listerner = new httplistener ())


Listerner. authenticationschemes = authenticationschemes. Anonymous; // specify the identity to authenticate anonymous access from anonymous.

Listerner. prefixes. Add ("http: // localhost: 8080/web /");

// Listerner. prefixes. Add ("http: // localhost/web /");

Listerner. Start ();

Console. writeline ("webserver start successed .......");

While (true)


// Wait for the request to connect

// Getcontext is blocked if no request exists

Httplistenercontext CTX = listerner. getcontext ();

CTX. response. statuscode = 200; // sets the HTTP status code returned to the client.

String name = CTX. Request. querystring ["name"];

If (name! = NULL)


Console. writeline (name );


// Use writer to output the HTTP response code

Using (streamwriter writer = new streamwriter (CTX. response. outputstream ))


Console. writeline ("hello ");

Writer. writeline ("<HTML>

Writer. writeline ("<Div style = \" height: 20px; color: Blue; text-align: center; \ "> <p> Hello {0} </P> </div>", name );

Writer. writeline ("<ul> ");

Foreach (string header in CTX. Request. headers. Keys)


Writer. writeline ("<li> <B> {0 }:</B> {1} </LI>", header, CTX. Request. headers [header]);


Writer. writeline ("</ul> ");

Writer. writeline ("</body>

Writer. Close ();

CTX. response. Close ();



Listerner. Stop ();





Enter http: // localhost: 8080/web/? in the browser /? Name = test or http: // localhost/web /? Name = test: Hello test and some request header information will appear in the browser.


1. a URI prefix string consists of a scheme (HTTP or HTTPS), a host, an optional port, and an optional path. An example of a complete prefix string is http://www.contoso.com: 8080/mermerdata /". The prefix must end with a forward slash. The httplistener object with a prefix that is the closest to the requested URI to respond to the request. Multiple httplistener objects cannot add the same prefix. If httplistener is used to add a prefix, A win32exception occurs.

2. If a port is specified, the host element can be replaced with "*" to indicate that if the requested URI does not match any other prefix, httplistener will accept the request sent to the port. For example, if any httplistener does not process the request URI, to receive all requests sent to port 8080, the prefix should be "http: // *: 8080 /". Similarly, to specify httplistener to accept all requests sent to the port, replace the host element with the "+" character, that is, "https: // +: 8080 ". The "*" and "+" characters can appear in the prefix of the included path.

3. The authenticationschemes enumeration class has the following values:

Anonymous: default value, which allows any client to connect without authentication.

Basic: requires a user name and password in plain text (64-bit encoding) for verification.

Digest: similar to basic identity authentication, but the user name and password are hashed for transmission using a simple password.

NTLM: Specifies NTLM authentication (only supported by IE ).

Integratedwindowsauthentication: Specify Windows authentication.

Negotiate: negotiate with the client to determine the authentication scheme. If both the client and server support Kerberos, Kerberos is used; otherwise, NTLM is used.

None: no authentication is performed.

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.