Web server and web server Construction
1. HTTP Protocol Introduction
HTTP is short for Hyper Text Transfer Protocol. Its development is the result of cooperation between the World Wide Web Consortium and the Internet team IETF (Internet Engineering Task Force). They finally published a series of RFC, RFC 1945 defines HTTP/1.0. The most famous one is RFC 2616. RFC 2616 defines a common version of HTTP 1.1.
HyperText Transfer Protocol (Hyper Text Transfer Protocol) is a Transfer Protocol used to Transfer HyperText from a WWW server to a local browser. It makes the browser more efficient and reduces network transmission. It not only ensures that the computer transfers hypertext documents correctly and quickly, but also determines which part of the transmitted documents and which part of the content is first displayed (such as text before graphics.
- HTTP is a TCP/IP-based communication protocol for data transmission (HTML files, image files, query results, etc ).
- HTTP is an application layer protocol consisting of requests and responses. It is a standard client server model.
- HTTP is a stateless protocol.
! [Upload is deeply imported into http .jpg failed. Please try again.]
The HTTP protocol always initiates a request from the client, and the server returns the response.
This restricts the use of the HTTP protocol and prevents the server from pushing messages to the client when the client does not initiate a request.
HTTP is a stateless protocol. This request on the same client does not correspond to the previous request.
2. http protocol analysis 1. browser requests
Http Request Method
We can correspond to the CRUD addition, deletion, modification, and query operations of the database:
2. Server Response
The HTTP response is divided into two parts: Header and Body (the Body is optional). The most important lines of the Header we see in the Network are as follows:
HTTP/1.1 200 OK
200 indicates a successful response, and OK is described later.
If the return value is not 200, other functions are often available, such
- 404 Not Found failed responses: the webpage does Not exist
- 500 Internal Server Error: an Internal Server Error occurs.
- ... And so on...
Httpstatus code .jpg
Content-Type: text/html
Content-Type indicates the response Content. text/html indicates the HTML webpage.
3. browser parsing process
After the browser reads the HTML source code of the Sina homepage, it parses the HTML and displays the page. Then, based on the various links in the HTML, it sends an HTTP request to the Sina server, get the corresponding images, videos, Flash, JavaScript scripts, CSS and other resources, and finally display a complete page.
3. Summary 1. HTTP request process
After tracking the Sina homepage, let's summarize the HTTP request process:
Step 1: The browser first sends an HTTP request to the server, including:
Method: GET or POST. GET only requests resources. POST will include user data;
Path:/full/url/path;
Domain Name: specified by the Host Header: Host: www.sina.com
And Other Related headers;
If it is POST, The request also includes a Body containing user data.
Step 2: The server returns an HTTP Response to the browser. The response includes:
Response Code: 200 indicates success, 3xx indicates redirection, 4xx indicates an error occurred in the request sent by the client, and 5xx indicates an error occurred during server processing;
Response Type: specified by Content-Type;
And Other Related headers;
Generally, the HTTP Response of the server carries content, that is, a Body containing the response content. The HTML source code of the webpage is in the Body.
Step 3: If the browser still needs to request other resources from the server, the browser sends an HTTP request again, repeat steps 1 and 2.
The HTTP protocol used by the Web adopts a very simple request-response mode, which greatly simplifies development. When writing a page, we only need to send HTML in the HTTP request, without considering how to attach images, videos, etc. If the browser needs to request images and videos, it sends another HTTP request. Therefore, an HTTP request only processes one resource (in this case, it can be understood as a short connection in the TCP protocol, and each link obtains only one resource, multiple links are required if multiple links are required)
HTTP protocol has strong scalability at the same time, although the browser requests the home page of the http://www.sina.com, but Sina in HTML can be linked to other server resources, such! [] (Http://upload-images.jianshu.io/upload_images/6078268-6060a9b222ef1412.png? ImageMogr2/auto-orient/strip % 7CimageView2/2/w/1240) to distribute the request pressure to each server, and one site can be linked to other sites, numerous websites are connected to each other to form the World Wide Web (WWW for short.
2. HTTP format
Client request information
Server Response Message
- Each HTTP request and response follow the same format. An HTTP request contains the Header and Body, and the Body is optional.
HTTP is a text protocol, so its format is also very simple.
Http get request format:
GET/path HTTP/1.1
Header1: Value1
Header2: Value2
Header3: Value3
Each Header has one row. The line break is \ r \ n or OS. linesep.
Http post request format:
POST/path HTTP/1.1
Header1: Value1
Header2: Value2
Header3: Value3
Body data goes here...
When two \ r \ n consecutive times occur, the Header part ends, and all the subsequent data is Body.
HTTP Response format:
200 OK
Header1: Value1
Header2: Value2
Header3: Value3
Body data goes here...
If an HTTP response contains a body, it is also separated by \ r \ n.
Note that the Body data Type is determined by the Content-Type header. For a webpage, the Body is text, and for an image, the Body is the binary data of the image.
When Content-Encoding exists, the Body data is compressed, and the most common compression method is gzip. Therefore, when you see Content-Encoding: gzip, You need to extract the Body data first, to get real data. The purpose of compression is to reduce the Body size and speed up network transmission.
4. Web static Server 1. Display fixed pages
Import socketimport multiprocessingimport osimport timedef serverHandler (clientSocket, clientAddr): 'interacts with the requested Client '# receives the message recvData = clientSocket from the client. recv (1, 1024 ). decode ('utf-8') print (recvData) # The server sends a message to the client as the response responseLine = 'HTTP/1.1 200 OK '+ OS. linesep responseHeader = 'server: laowang '+ OS. linesep responseHeader + = 'date: % s' % time. ctime () + OS. linesep responseBody = 'difference 1.1 meters 8' sendData = (responseLine + responseHeader + OS. linesep + responseBody ). encode ('gbk') clientSocket. send (sendData) # disable clientSocket. close () def main (): 'program portal '# socket object serverSocket = socket. socket (socket. AF_INET, socket. SOCK_STREAM) # The bound port number, which can be reused # serverSocket. setsockopt (socket. SOL_SOCKET, socket. SO_REUSEADDR, 1) # bind serverSocket. bind ('', 8000) # Listen to serverSocket. listen () while True: # receive clientSocket, clientAddr = serverSocket. accept () print (clientSocket) # open a new process and execute interactive multiprocessing. process (target = serverHandler, args = (clientSocket, clientAddr )). start () # disable Client object clientSocket. close () if _ name _ = '_ main _': main ()
Client browser page 2. display the required page
Import time, multiprocessing, socket, OS, reG_PATH = '. /html 'def serveHandler (clientSocket, clientAddr): recvData = clientSocket. recv (1, 1024 ). decode ('gbk') lineFirst = recvData. splitlines () [0] strFirst = re. split (R' + ', lineFirst) fileName = strFirst [1] filePath = G_PATH if'/'= fileName: filePath + = '. /index.html 'else: filePath + = fileName try: file = None file = open (filePath, 'R', encoding = 'gbk') respons EBody = file. read () responseLine = 'HTTP/1.1 200 OK '+ OS. linesep responseHeader = 'server: erbai' + OS. linesep responseHeader + = 'date: % s' % time. ctime () + OS. linesep response t FileNotFoundError: responseLine = 'HTTP/1.1 404 not found '+ OS. linesep responseHeader = 'server: erbai' + OS. linesep responseHeader + = 'date: % s' % time. ctime () + OS. linesep responseBody = 'sorry, the content you want cannot be found in the server' response t Excep Tion: responseLine = 'HTTP/1.1 500 error' + OS. linesep responseHeader = 'server: erbai' + OS. linesep responseHeader + = 'date: % s' % time. ctime () + OS. linesep responseBody = 'the server is being maintained. Please try again later. 'Finally: if file! = None and not file. closed: file. close () senData = (responseLine + responseHeader + OS. linesep + responseBody ). encode ('gbk') clientSocket. send (senData) clientSocket. close () def main (): serveSocket = socket. socket (socket. AF_INET, socket. SOCK_STREAM) serveSocket. bind ('', 8000) serveSocket. listen () while True: clientSocket, clientAddr = serveSocket. accept () print (clientSocket) multiprocessing. process (target = serveHandler, args = (clientSocket, clientAddr )). start () clientSocket. close () if _ name _ = '_ main _': main ()
Client browser Homepage
Customer browser biye.html page
If you have any questions during the learning process or want to obtain learning resources, join the learning exchange group.
343599877. Let's learn the front-end together!