Python Network Programming - Static Web Server Implementation

Overview


The specified page of the request can be returned. If there is no requested file, 404 status information will be returned.

Implementation steps


1. Import socket and os packages
import socket
import os

2. Create a tcp server socket
tcp_server_socket = socket.socket ( socket.AF_INET , socket.SOCK_STREAM ) _ _ _ _ _ _

3. Bind the port number
tcp_server_socket.bind (( " " , 8000 ) )

4. Set up monitoring
tcp_server_socket.listen ( 128 ) _ _

5. Waiting to accept the connection request from the client
new_socket , ip_port = tcp_server_socket.accept ( ) _

6. Receive the request information from the client
recv_data = new_socket.recv ( 4096 ) _ _
# Determine whether the received data length is 0
if len ( recv_data ) == 0 :
new_socket.close ( ) _
return

7. Decode the binary data
recv_content = recv_data.decode ( " utf -8" )
print ( recv_content )

8. Split the data by spaces
request_list = recv_content.split ( " " , maxsplit = 2 ) _

9. Get the requested resource path
request_path = request_list [ 1 ]
print ( request_path )

10. Determine whether the request is the root directory, if it is the information returned by the root directory setting
if request_path == "/" :
request_path = "/index.html"

11. Packet processing
try :
# Open the file to read the data in the file, prompt: use rb mode here, which is compatible with opening image files
with open ( "static" + request_path , "rb" ) as file : # where file represents the object that opened the file
file_data = file.read ( ) _
# Tip: with open to close the file, this step does not need to be done by the programmer, the system does it for us
except Exception as e :
# The code is executed here, indicating that there is no requested file, and returning 404 status information
# response line
response_line = "HTTP/1.1 404 Not Found "
# response header
response_header = "Server: PWS/1.0 "
# Read 404 page data
with open ( "static/error.html" , "rb" ) as file :
file_data = file.read ( ) _

# response body
response_body = file_data

# Encapsulate data into http response message format data
response = ( response_line +
response_header +
" " ) .encode ( "utf-8" ) + response_body

# Response message data sent to the browser
new_socket.send ( response ) _ _

else :
# The code is executed here, indicating that the file exists, and returning 200 status information
# response line
response_line = "HTTP/1.1 200 OK "
# response header
response_header = "Server: PWS/1.0 "
# response body
response_body = file_data

# Encapsulate data into http response message format data
response = ( response_line +
response_header +
" " ) .encode ( "utf-8" ) + response_body

# Response message data sent to the browser
new_socket.send ( response ) _ _
finally :
# Close the socket serving the client
new_socket.close ( ) _

Code



import socket
import os


def main ():
# create tcp server socket
tcp_server_socket = socket.socket ( socket.AF_INET , socket.SOCK_STREAM ) _ _ _ _ _ _
# Set the port number multiplexing, the program exits the port number and releases it immediately
tcp_server_socket.setsockopt ( socket.SOL_SOCKET , socket.SO_REUSEADDR , True ) _ _ _ _ _ _
# bind port number
tcp_server_socket.bind (( " " , 8000 ) )
# set monitor
tcp_server_socket.listen ( 128 ) _ _
# Loop waiting to accept the connection request from the client
while True :
# Waiting to accept the connection request from the client
new_socket , ip_port = tcp_server_socket.accept ( ) _
# The code is executed here, indicating that the connection is successfully established
# Receive the request information from the client
recv_data = new_socket.recv ( 4096 ) _ _
# Determine whether the received data length is 0
if len ( recv_data ) == 0 :
new_socket.close ( ) _
return

# decode binary data
recv_content = recv_data.decode ( " utf -8" )
print ( recv_content )

# split the data by spaces
request_list = recv_content.split ( " " , maxsplit = 2 ) _
# Get the requested resource path
request_path = request_list [ 1 ]
print ( request_path )

# Determine whether the request is the root directory, if it is the information returned by the root directory setting
if request_path == "/" :
request_path = "/index.html"

# 1. os.path.exits
# os.path.exists("static/" + request_path)
# 2. try-except

try :
# Open the file to read the data in the file, prompt: use rb mode here, which is compatible with opening image files
with open ( "static" + request_path , "rb" ) as file : # where file represents the object that opened the file
file_data = file.read ( ) _
# Tip: with open to close the file, this step does not need to be done by the programmer, the system does it for us
except Exception as e :
# The code is executed here, indicating that there is no requested file, and returning 404 status information
# response line
response_line = "HTTP/1.1 404 Not Found "
# response header
response_header = "Server: PWS/1.0 "
# Read 404 page data
with open ( "static/error.html" , "rb" ) as file :
file_data = file.read ( ) _

# response body
response_body = file_data

# Encapsulate data into http response message format data
response = ( response_line +
response_header +
" " ) .encode ( "utf-8" ) + response_body

# Response message data sent to the browser
new_socket.send ( response ) _ _

else :
# The code is executed here, indicating that the file exists, and returning 200 status information
# response line
response_line = "HTTP/1.1 200 OK "
# response header
response_header = "Server: PWS/1.0 "
# response body
response_body = file_data

# Encapsulate data into http response message format data
response = ( response_line +
response_header +
" " ) .encode ( "utf-8" ) + response_body

# Response message data sent to the browser
new_socket.send ( response ) _ _
finally :
# Close the socket serving the client
new_socket.close ( ) _


# Determine whether it is the code of the main module
if __name__ == '__main__' :
main ()



Copyright statement: The content of this article is contributed by Alibaba Cloud's real-name registered users. The copyright belongs to the original author. The Alibaba Cloud developer community does not own the copyright and does not assume the corresponding legal responsibility. For specific rules, please refer to the " Alibaba Cloud Developer Community User Service Agreement " and " Alibaba Cloud Developer Community Intellectual Property Protection Guidelines ". If you find any content suspected of plagiarism in this community, fill out the infringement complaint form to report it. Once verified, this community will delete the allegedly infringing content immediately.

Related Articles

Explore More Special Offers

  1. Short Message Service(SMS) & Mail Service

    50,000 email package starts as low as USD 1.99, 120 short messages start at only USD 1.00