Development of HTTP static Web server in Python

As we all know, Http protocol is a browser to server communication protocol based on Tcp protocol. Its basic principle is also to communicate through socket.

When using HTTP protocol for communication, it is necessary to note that there is no problem with the format of the response message returned.

The response message consists of four parts: response line, response header, blank line and response body. Each data must be separated by / r/n.

Blank line is the necessary data to distinguish response header and response body, which cannot be omitted.

The main development ideas of HTTP static Web server are as follows:

1. Import socket module

2. Create socket object

3. Set port multiplexing to solve port blocking problem

4. Bind port and IP. After binding port and IP, client can only send request message to server through bound IP and port.

5. Set monitoring,

Note: after the monitoring is set successfully, the original socket becomes a passive socket and cannot receive or send data.

6. Wait for client (browser) link (send request)

7. Send and receive data using the new socket returned after the link is successful.

Note: the data returned here should be HTTP response message.

 1 # 1.Import module
 2 import socket
 3 
 4 
 5 def main():
 6     # 2.Establish socket object
 7     server_socket = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
 9     # 3.Set up port multiplexing
10     server_socket.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR, True)
11     # 4.Binding port
12     server_socket.bind(('', 8001))
13     # 5.Set up monitoring
14     server_socket.listen(128)
15     # Set cyclic receiving client connection to realize multi client connection
16     while True:
17         # 6.Receive client connection
18         client_socket, ip_port = server_socket.accept()
19         print("Client:%s Online.,The use port is:%s" % ip_port)
20         # 7.receive data
21         recv_data = client_socket.recv(1024).decode('utf-8')
22         if recv_data:
23             # print('The received data is:', recv_data)
24             # Obtain http Specified path in request message
25             # split()Method does not specify parameters, the default is blank characters(\t,\n,Space) split
26             # After the obtained path information is divided, three parts will be stored in the list
27             # 1.How to submit the request: GET/POST
28             # 2.Request path information and parameter information
29             # 3.HTTP Agreement and version
30             page_recv_data = recv_data.split()[1]
31             print('The requested resource path is:', page_recv_data)
32             # Judge whether the received path information contains parameters
33             # HTTP In the protocol, the parameter format is:/index.html?name=666&age=12
34             if '?' in page_recv_data:
35                 real_recv_page = page_recv_data.split('?')[0]
36             else:
37                 real_recv_page = page_recv_data
38             try:
39                 # 8.send data
40 
41                 # Receive the specified path information and read the file information
42                 # Be careful f-string Only 3.6 And above
43                 data = f'static{real_recv_page}'
44                 print(data)
45                 with open(data, 'rb') as file:
46                     page_data = file.read()
47             except Exception as e:
48                 # 8.1 Write when file does not exist HTTP The form of agreement is as follows:
49                 http_line = 'HTTP/1.1 / 404 NOT FOUND\r\n'
50                 http_header = 'Server: PWS/1.0\r\n'
51                 http_body = '<h1>Page Not Found!</h1>'
52                 send_data = (http_line + http_header + '\r\n' + http_body).encode()
53                 client_socket.send(send_data)
54             else:
55                 # 8.1 Write when file exists HTTP The form of agreement is as follows:
56                 http_line = 'HTTP/1.1 / 200 ok\r\n'
57                 http_header = 'Server: PWS/1.0\r\n'
58                 send_data = (http_line + http_header + '\r\n').encode() + page_data
59                 client_socket.send(send_data)
60             finally:
61                 # Disconnect from client
62                 client_socket.close()
63         else:
64             print('Client:%s,Port number:%s Offline.' % ip_port)
65             break
66 
67     # 9.Close socket
68     # Shut down the server
69     # server_socket.close()
70 
71 
72 # Entrance
73 if __name__ == '__main__':
74     main()

Keywords: Programming socket Web Server

Added by danieloberg on Fri, 13 Dec 2019 23:33:03 +0200