Home Backend Development C#.Net Tutorial C# implements the simplest HTTP server

C# implements the simplest HTTP server

Nov 24, 2016 am 11:48 AM
c# http server

Introduction

This article uses C# to implement the simplest HTTP server class. You can embed it into your own project, or you can read the code to learn about the HTTP protocol.

Background

High-performance WEB applications are generally installed on powerful WEB servers, such as IIS, Apache, and Tomcat. However, HTML is a very flexible UI markup language, which means that any application and back-end service can provide HTML generation support. In this small example, servers like IIS and Apache consume too many resources. We need to implement a simple HTTP server ourselves and embed it into our application to handle WEB requests. We only need one class to implement it, it's very simple.

 Code Implementation

 First let’s review how to use classes, and then we’ll analyze the specific details of the implementation. Here we create a class that inherits from HttpServer and implements the two abstract methods handleGETRequest and handlePOSTRequest:

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("<html><body><h1>test server</h1>");
        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("<html><body><h1>test server</h1>");
        p.outputStream.WriteLine("<a href=/test>return</a><p>");
        p.outputStream.WriteLine("postbody: <pre class="brush:php;toolbar:false">{0}
", data); } }
Copy after login

When starting to process a simple request, we need to start a separate thread to listen to a port, such as port 8080 :

HttpServer httpServer = new MyHttpServer(8080);
Thread thread = new Thread(new ThreadStart(httpServer.listen));
thread.Start();
Copy after login

If you compile and run this project, you will see the sample content generated on the page under the browser http://localhost:8080 address. Let's take a brief look at how this HTTP server engine is implemented.

 This WEB server consists of two components. One is the HttpServer class that is responsible for starting TcpListener to listen to the specified port, and uses the AcceptTcpClient() method to process TCP connection requests in a loop, which is the first step in processing TCP connections. Then the request arrives at the "specified" port, and a new pair of ports is created to initialize the TCP connection from the client to the server. This pair of ports is the session of TcpClient, so that our main port can continue to receive new connection requests. From the code below, we can see that each time the listener creates a new TcpClien, the HttpServer class creates a new HttpProcessor, and then starts a thread to operate. The HttpServer class also contains two abstract methods, which you must implement.

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);
}
Copy after login

In this way, a new tcp connection is processed by HttpProcessor in its own thread. The job of HttpProcessor is to correctly parse the HTTP header and control the correctly implemented abstract method. Let's take a look at the processing of HTTP headers. The first line of code for the HTTP request is as follows:

GET /myurl HTTP/1.0
Copy after login

After setting the input and output of process(), HttpProcessor will call the parseRequest() method.

public void parseRequest() {
    String request = inputStream.ReadLine();
    string[] tokens = request.Split(&#39; &#39;);
    if (tokens.Length != 3) {
        throw new Exception("invalid http request line");
    }
    http_method = tokens[0].ToUpper();
    http_url = tokens[1];
    http_protocol_versionstring = tokens[2];
 
    Console.WriteLine("starting: " + request);
}
Copy after login

HTTP requests consist of 3 parts, so we only need to use the string.Split() method to split them into 3 parts. The next step is to receive and parse the HTTP header information from the client, each line in the header information The data is saved in the form of Key-Value (key-value). A blank line indicates the end of the HTTP header information. We use the readHeaders method in our code to read the HTTP header information:

public void readHeaders() {
    Console.WriteLine("readHeaders()");
    String line;
    while ((line = inputStream.ReadLine()) != null) {
        if (line.Equals("")) {
            Console.WriteLine("got headers");
            return;
        }
 
        int separator = line.IndexOf(&#39;:&#39;);
        if (separator == -1) {
            throw new Exception("invalid http header line: " + line);
        }
        String name = line.Substring(0, separator);
        int pos = separator + 1;
        while ((pos < line.Length) && (line[pos] == &#39; &#39;)) {
            pos++; // 过滤掉所有空格
        }
 
        string value = line.Substring(pos, line.Length - pos);
        Console.WriteLine("header: {0}:{1}",name,value);
        httpHeaders[name] = value;
    }
}
Copy after login

So far, we have learned how to handle simple GET and POST requests are assigned to the correct handler respectively. In this example, there is a thorny problem that needs to be dealt with when sending data, that is, the request header information contains the length information of the sent data, content-length. When we hope that the handlePOSTRequest method in the subclass HttpServer can handle the data correctly, we The data length content-length information needs to be put into the data stream together, otherwise the sender will be blocked waiting for data that will never arrive. We use a less elegant but very effective way to handle this situation, which is to read the data into a MemoryStream before sending it to the POST processing method. This approach is less than ideal for the following reasons: if the data being sent is large, or even uploading a file, then it is not appropriate or even possible for us to cache the data in memory. The ideal method is to limit the length of the post. For example, we can limit the data length to 10MB.

Another simplification of this simple version of the HTTP server is the return value of content-type. In the HTTP protocol, the server always sends the MIME-Type of the data to the client to tell the client what type of data it needs to receive. In the writeSuccess() method, we see that the server always sends text/html type. If you need to add other types, you can extend this method.


Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn

Hot AI Tools

Undresser.AI Undress

Undresser.AI Undress

AI-powered app for creating realistic nude photos

AI Clothes Remover

AI Clothes Remover

Online AI tool for removing clothes from photos.

Undress AI Tool

Undress AI Tool

Undress images for free

Clothoff.io

Clothoff.io

AI clothes remover

AI Hentai Generator

AI Hentai Generator

Generate AI Hentai for free.

Hot Article

R.E.P.O. Energy Crystals Explained and What They Do (Yellow Crystal)
2 weeks ago By 尊渡假赌尊渡假赌尊渡假赌
Repo: How To Revive Teammates
4 weeks ago By 尊渡假赌尊渡假赌尊渡假赌
Hello Kitty Island Adventure: How To Get Giant Seeds
3 weeks ago By 尊渡假赌尊渡假赌尊渡假赌

Hot Tools

Notepad++7.3.1

Notepad++7.3.1

Easy-to-use and free code editor

SublimeText3 Chinese version

SublimeText3 Chinese version

Chinese version, very easy to use

Zend Studio 13.0.1

Zend Studio 13.0.1

Powerful PHP integrated development environment

Dreamweaver CS6

Dreamweaver CS6

Visual web development tools

SublimeText3 Mac version

SublimeText3 Mac version

God-level code editing software (SublimeText3)

Active Directory with C# Active Directory with C# Sep 03, 2024 pm 03:33 PM

Guide to Active Directory with C#. Here we discuss the introduction and how Active Directory works in C# along with the syntax and example.

Access Modifiers in C# Access Modifiers in C# Sep 03, 2024 pm 03:24 PM

Guide to the Access Modifiers in C#. We have discussed the Introduction Types of Access Modifiers in C# along with examples and outputs.

Random Number Generator in C# Random Number Generator in C# Sep 03, 2024 pm 03:34 PM

Guide to Random Number Generator in C#. Here we discuss how Random Number Generator work, concept of pseudo-random and secure numbers.

C# Data Grid View C# Data Grid View Sep 03, 2024 pm 03:32 PM

Guide to C# Data Grid View. Here we discuss the examples of how a data grid view can be loaded and exported from the SQL database or an excel file.

C# StringReader C# StringReader Sep 03, 2024 pm 03:23 PM

Guide to C# StringReader. Here we discuss a brief overview on C# StringReader and its working along with different Examples and Code.

Patterns in C# Patterns in C# Sep 03, 2024 pm 03:33 PM

Guide to Patterns in C#. Here we discuss the introduction and top 3 types of Patterns in C# along with its examples and code implementation.

C# StringWriter C# StringWriter Sep 03, 2024 pm 03:23 PM

Guide to C# StringWriter. Here we discuss a brief overview on C# StringWriter Class and its working along with different Examples and Codes.

BinaryWriter in C# BinaryWriter in C# Sep 03, 2024 pm 03:22 PM

Guide to BinaryWriter in C#. Here we discuss syntax and explanation, how it works with examples to implement with proper codes.

See all articles