Python Network Programming - Object Oriented Static Web Server

Object Oriented Static Web Server Introduction:

Object Oriented Static Web Server.The Web server is abstracted into a class, the method is initialized, and the socket line is established in the initialization. Provides a method to start the web server and let the web server process the client's request.

Object Oriented Static Web Server Overview

The Web server is abstracted into a class, the method is initialized, and the socket line is established in the initialization. Provides a method to start the web server and let the web server process the client's request.

Implementation steps

1. Object Oriented Static Web Server.Define the web server class


initialization class
class HttpWebServer ( object ):
def __init __ ( self ) :
# 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 and releases it immediately
tcp_server_ socket . setsockopt ( socket . SOL_SOCKET , socket . SO_REUSEADDR , True )
# bind port number
tcp_server_socket.bind ( ( " " , 9000 ) )
# set monitor
tcp_server_socket.listen ( 128 ) _ _ _
# Save the successfully created server socket
self.tcp_server_socket _ _ = tcp_server_socket

Handling client requests
@staticmethod _
def handle_client_request ( new_socket ):
# The code is executed here, indicating that the connection is successfully established
recv_client_data = new_socket.recv ( 4096 ) _ _ _
if len ( recv_client_data ) == 0 :
print ( "close the browser" )
new_socket.close ( ) _ _
return

# decode binary data
recv_client_content = recv_client_data.decode ( " utf - 8" )
print ( recv_client_content )
# Split according to the specified string, the maximum number of splits is specified as 2
request_list = recv_client_content.split ( " " , maxsplit = 2 ) _ _

# Get the request resource path
request_path = request_list [ 1 ] _
print ( request_path )

# Determine whether the request is the root directory, if the condition is true, specify the home page data to return
if request_path == "/" :
request_path = "/index.html"

try :
# Dynamically open the specified file
with open ( "static" + request_path , " rb " ) as file :
# read file data
file_data = file.read ( ) _
except Exception as e :
# The requested resource does not exist, return 404 data
# response line
response_line = "HTTP/1.1 404 Not Found "
# response header
response_header = "Server: PWS1.0 "
with open ( "static/error.html" , " rb " ) as file :
file_data = file.read ( ) _
# response body
response_body = file_data

# Concatenate the response message
response_data = ( response_line + response_header + " " ) .encode ( "utf-8" ) + response_body
# send data
new_socket.send ( response_data ) _ _ _
else :
# response line
response_line = "HTTP/1.1 200 OK "
# response header
response_header = "Server: PWS1.0 "

# response body
response_body = file_data

# Concatenate the response message
response_data = (response_line + response_header + " ").encode("utf-8") + response_body
# 发送数据
new_socket.send(response_data)
finally:
# Close the socket between the service and the client
new_socket.close ( ) _ _

2. Object Oriented Static Web Server.Start the web server to work


def start ( self ):
while True :
# Waiting to accept the connection request from the client
new_socket , ip_port = self.tcp_server_socket.accept ( ) _ _ _ _
# When the client and the server establish a connection process, create a child thread
sub_thread = threading . Thread ( target = self . handle_client_request , args = ( new_socket ,))
# Set the daemon main thread
sub_thread.setDaemon ( True ) _ _ _
# Start the child thread to execute the corresponding task
sub_thread.start ( ) _ _

Code
import socket
import threading


# Define the web server class
class HttpWebServer ( object ):
def __init __ ( self ) :
# 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 and releases it immediately
tcp_server_ socket . setsockopt ( socket . SOL_SOCKET , socket . SO_REUSEADDR , True )
# bind port number
tcp_server_socket.bind ( ( " " , 9000 ) )
# set monitor
tcp_server_socket.listen ( 128 ) _ _ _
# Save the successfully created server socket
self.tcp_server_socket _ _ = tcp_server_socket

# handle client requests
@staticmethod _
def handle_client_request ( new_socket ):
# The code is executed here, indicating that the connection is successfully established
recv_client_data = new_socket.recv ( 4096 ) _ _ _
if len ( recv_client_data ) == 0 :
print ( "close the browser" )
new_socket.close ( ) _ _
return

# decode binary data
recv_client_content = recv_client_data.decode ( " utf - 8" )
print ( recv_client_content )
# Split according to the specified string, the maximum number of splits is specified as 2
request_list = recv_client_content.split ( " " , maxsplit = 2 ) _ _

# Get the request resource path
request_path = request_list [ 1 ] _
print ( request_path )

# Determine whether the request is the root directory, if the condition is true, specify the home page data to return
if request_path == "/" :
request_path = "/index.html"

try :
# Dynamically open the specified file
with open ( "static" + request_path , " rb " ) as file :
# read file data
file_data = file.read ( ) _
except Exception as e :
# The requested resource does not exist, return 404 data
# response line
response_line = "HTTP/1.1 404 Not Found "
# response header
response_header = "Server: PWS1.0 "
with open ( "static/error.html" , " rb " ) as file :
file_data = file.read ( ) _
# response body
response_body = file_data

# Concatenate the response message
response_data = ( response_line + response_header + " " ) .encode ( "utf-8" ) + response_body
# send data
new_socket.send ( response_data ) _ _ _
else :
# response line
response_line = "HTTP/1.1 200 OK "
# response header
response_header = "Server: PWS1.0 "

# response body
response_body = file_data

# Concatenate the response message
response_data = (response_line + response_header + " ").encode("utf-8") + response_body
# 发送数据
new_socket.send(response_data)
finally:
# Close the socket between the service and the client
new_socket.close ( ) _ _

# Start the web server to work
def start ( self ):
while True :
# Waiting to accept the connection request from the client
new_socket , ip_port = self.tcp_server_socket.accept ( ) _ _ _ _
# When the client and the server establish a connection process, create a child thread
sub_thread = threading . Thread ( target = self . handle_client_request , args = ( new_socket ,))
# Set the daemon main thread
sub_thread.setDaemon ( True ) _ _ _
# Start the child thread to execute the corresponding task
sub_thread.start ( ) _ _


# Program entry function
def main ( ):
# Create web server object
web_server = HttpWebServer ( )
# Start the web server to work
web_server.start ( ) _ _


if __name__ == '__main__' :
main ( )

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