Build a Web server (1)

Source: Internet
Author: User

Build a Web server (1)
GuideI believe that if you want to become a better developer, you must have a deeper understanding of the internal structure of the software system used in daily use, including programming languages, compilers and interpreters, databases and operating systems, Web servers, and Web frameworks. In addition, to better understand these systems, you must rebuild them from scratch with one brick to one tile.

One day, a walking Lady happened to pass by a construction site and saw three working workers. She asked the first person, "what are you doing ?" The first man shouted angrily: "Didn't you see that I am building bricks ?" The woman was not satisfied with the answer, so she asked the second person, "what are you doing ?" The second person replied, "I am building a brick wall ." After that, he turned to the first person and said to him, "Hi, you have overbuilt the wall. Get the Brick !" However, the woman was still dissatisfied with the answer, so she asked the third person the same question. The third person looked up and said to her, "I am building the largest church in the world ." When he answered, the first man and the second man quarrelled about the wrong brick. He turned to the two men and said, "You don't have to worry about that brick. The wall is indoors, and it will be filled with cement, and no one will see it. Let's build the next layer ."

This story tells us: If you can understand the structure of the entire system and how the components of the system are combined (such as bricks, walls, and churches ), you can quickly locate and fix the problem (the wrong Brick ).

What do you need to do if you want to create a Web server from scratch?

I believe that if you want to become a better developerYou must have a deeper understanding of the internal structure of the software system that is commonly used, including programming languages, compilers and interpreters, databases and operating systems, Web servers, and Web frameworks. To better understand these systemsThe system must be rebuilt from the ground up with one brick to one tile.

Xunzi used these words to express this idea:

"It is not easy to hear.I hear and I forget."

"It is easy to hear.I see and I remember."

"It is unknown.I do and I understand."

I hope you can now realize that it is a good idea to re-build a software system to understand how it works.

In this series of three articles, I will teach you how to build your own Web servers. Let's get started ~

The first question is: what is a Web server?

In short, it is a network server (ah, server set server) running on a physical server, waiting for the client to send a request to it. After receiving the request, it generates a response and sends it back to the client. The client and server communicate with each other through the HTTP protocol. The client can be your browser or any other software that uses the HTTP protocol.

What is the simplest Web server implementation? Here I will provide my implementation. This example is written in Python, even if you have never heard of Python (it is a super easy-to-use language, please try it !), You should also be able to understand the concept in code and comments:

import socketHOST, PORT = '', 8888listen_socket = socket.socket(socket.AF_INET, socket.SOCK_STREAM)listen_socket.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR, 1)listen_socket.bind((HOST, PORT))listen_socket.listen(1)print 'Serving HTTP on port %s ...' % PORTwhile True:    client_connection, client_address = listen_socket.accept()    request = client_connection.recv(1024)    print request    http_response = """/HTTP/1.1 200 OKHello, World!"""    client_connection.sendall(http_response)    client_connection.close()

Save the preceding code as webserver1.py or download the file directly from GitHub. Then, run the program in the command line. Like this:

$ python webserver1.pyServing HTTP on port 8888 …

Enter URL: http: // localhost: 8888/hello in the address bar of your web browser, and press enter to witness the miracle. You should see "Hello, World !" Display in your browser, as shown in the following figure:

To be honest, try it now. I will wait for you when you do the experiment.

Finished? Good! Now let's discuss how it actually works.

First, we start with the Web address you just entered. It is calledURL, which is its basic structure:

The URL is the address of a Web server. The browser uses this address to search for and connect to the Web server and return the above content to you. Before your browser can send an HTTP request, it needs to establish a TCP connection with the Web server. Then, an HTTP request is sent in the TCP connection and the server returns an HTTP response. When your browser receives a response, its content is displayed. In the preceding example, it displays "Hello, World !".

We will further explore the process of establishing a TCP connection between the client and the server before sending an HTTP request. To establish links, they use the so-called"SocketSocket". We do not directly use a browser to send requests, but useTelnet to manually simulate this process.

On the computer where you run the Web server, create a telnet session in the command line, specify a local domain name, use port 8888, and press Enter:

$ telnet localhost 8888Trying 127.0.0.1 …Connected to localhost.

At this time, you have established a TCP connection with the server running on your local host. In, you can see a basic process from the beginning of a server to the ability to establish a TCP connection.

In the same telnet session, enterGET/hello HTTP/1.1 and press Enter:

$ telnet localhost 8888Trying 127.0.0.1 …Connected to localhost.GET /hello HTTP/1.1HTTP/1.1 200 OKHello, World!

You just manually simulated your browser (work )! You have sent an HTTP request and received an HTTP response. The basic structure of an HTTP request is as follows:

The first line of an HTTP request consists of three parts: the HTTP method (GET, because we want our server to return some content) and indicate the path of the required page.Hello, there are also Protocol versions.

For simplicity, the Web server we just built completely ignores the above request content. You can also try to input useless content instead of "GET/hello HTTP/1.1", but you will still receive a "Hello, World !" Response.

Once you enter the request line and press enter, the client will send the request to the server. When the server reads the request line, it will return the corresponding HTTP response.

The following is the response content of the client returned by the server (telnet in the preceding example:

Let's parse it. This response consists of three parts: a status lineHTTP/1.1 200 OK, followed by a blank line, followed by the response body.

The HTTP status line HTTP/1.1 200 OK contains the HTTP Version Number, HTTP status code, and HTTP status phrase "OK ". When the browser receives the response, it displays the response body, which is why "Hello, World!" is displayed in the browser !".

The above is the basic working model of Web servers. To sum up, the Web server creates a socket in the listening state and receives new connections cyclically. After a TCP connection is established, the client sends an HTTP request to the server. Then, the server responds with an HTTP response, and the client displays the HTTP Response content to the user. To establish a TCP connection, both the client and server use sockets.

Now, you should understand the basic working methods of Web servers. You can use a browser or other HTTP clients for testing. If you have tried and observed, you should also be able to use telnet to manually write HTTP requests and become a "Humanoid" HTTP client.

Now let's leave a small question: "How do you adapt to Django, Flask, or Pyramid applications on the Web server you just set up without making any changes to the program ?"

I will explain it in detail in the second part of this series. Coming soon.

By the way, I am writing a book titled building a Web server: starting from scratch. This book explains how to write a basic Web server from the beginning, which contains more details not found in this article. Subscribe to the email list to get the latest progress and release date of the book.

From: https://linux.cn/article-7662-1.html

Address: http://www.linuxprobe.com/get-web-servers.html


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.