C # implement HTTP mini server (two methods)

Source: Internet
Author: User
Tags apache tomcat

This article uses two slightly different methods to implement HTTP server classes in C # language. The reason for writing this is to have a better understanding of the underlying operations of HTTP.

To complete high-performance Web service functions, we usually need to write to services, such as IIS and Apache Tomcat. However, we all know the complexity of Web server configuration. If we only need some simple functions, installing these components does not seem necessary. What we need is a simple HTTP class that can be easily embedded into simple Web request services and added to our own programs.

Method 1:
There is a simple but powerful class HttpListener under the. net Framework. This class of code can complete a simple server function. Although the following content has almost no value in actual operation, it is also a good way to understand the detailed principles of the HTTP request process.
Copy codeThe Code is as follows:
HttpListener httpListener = new HttpListener ();
HttpListener. AuthenticationSchemes = AuthenticationSchemes. Anonymous;
HttpListener. Prefixes. Add ("http: // localhost: 8080 /");
HttpListener. Start ();
New Thread (new ThreadStart (delegate
{
While (true)
{
HttpListenerContext httpListenerContext = httpListener. GetContext ();
HttpListenerContext. Response. StatusCode = 200;
Using (StreamWriter writer = new StreamWriter (httpListenerContext. Response. OutputStream ))
{
Writer. writeLine ("Writer. writeLine ("<div style = \" height: 20px; color: blue; text-align: center; \ "> <p> hello </p> </div> ");
Writer. WriteLine ("<ul> ");
Writer. WriteLine ("</ul> ");
Writer. WriteLine ("</body> }
}
}). Start ();

If you use it well, such a simple class may receive unexpected results. However, the HttpListener class perfectly encapsulates the underlying layer, leading to the loss of flexibility in Protocol control, therefore, I think this class will not be used in large server programs. Therefore, if necessary, encapsulate a class using the Tcp protocol to better control the service running status.

Implementation Method 2:
This method is shared by a foreigner. Although the file content looks messy, the logic is very organized. Let's analyze the implementation process:
The implementation is provided by subclass HttpServer and two Abstract METHODS handlegetrequest and handlepostrequest...
Copy codeThe Code is as follows:
Public class MyHttpServer: HttpServer {
Public MyHttpServer (int port)
: Base (port ){
}
Public override void handleGETRequest (HttpProcessor p ){
Console. WriteLine ("request: {0}", p. http_url );
P. writeSuccess ();
P. outputStream. WriteLine ("P. outputStream. WriteLine ("Current Time:" + DateTime. Now. ToString ());
P. outputStream. WriteLine ("url: {0}", p. http_url );
P. outputStream. WriteLine ("<form method = post action =/form> ");
P. outputStream. WriteLine ("<input type = text name = foo value = foovalue> ");
P. outputStream. WriteLine ("<input type = submit name = bar value = barvalue> ");
P. outputStream. WriteLine ("</form> ");
}
Public override void handlePOSTRequest (HttpProcessor p, StreamReader inputData ){
Console. WriteLine ("POST request: {0}", p. http_url );
String data = inputData. ReadToEnd ();
P. outputStream. WriteLine ("P. outputStream. WriteLine ("<a href =/test> return </a> <p> ");
P. outputStream. WriteLine ("postbody: <pre >{ 0} </pre>", data );
}
}

If you can smoothly compile and run the project in the attachment, you should be able to enter Http: // localhost: 8080/in a Web browser. Then you can view the simple HTML page rendering above. Let's see how it is implemented ~!

This simple Web server can be divided into two parts. The HttpServer class enables a TcpListener instance that specifies the input port and uses accepttcpclient () to process incoming TCP connection requests cyclically. This is the first step to process incoming TCP connections. When the incoming request arrives at a known specified port, a new server and client port pair will be created during the acceptance process for connection and communication between the server language client.
Copy codeThe Code is as follows:
View Code
Public abstract class HttpServer {
Protected int port;
TcpListener listener;
Bool is_active = true;
Public HttpServer (int port ){
This. port = port;
}
Public void listen (){
Listener = new TcpListener (port );
Listener. Start ();
While (is_active ){
TcpClient s = listener. AcceptTcpClient ();
HttpProcessor processor = new HttpProcessor (s, this );
Thread thread = new Thread (new ThreadStart (processor. process ));
Thread. Start ();
Thread. Sleep (1 );
}
}
Public abstract void handleGETRequest (HttpProcessor p );
Public abstract void handlePOSTRequest (HttpProcessor p, StreamReader inputData );
}

Such an introduction may make people feel confused, and it may be easier to understand the code or debug the sample code program intuitively. Next we will post the source code for your reference, hoping to help you!
Click to download

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.