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 ("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.


Note:

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.