Python面向对象封装多线程web服务器
利用socket模块与threading模块进行编写
根据此专栏Web服务器功能的组合
import socket
import threading
import os
class HttpWebServer(object):
def __init__(self):
tcp_server_socket = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
tcp_server_socket.setsockopt(socket.SOL_SOCKET, socket.SOCK_STREAM, True)
tcp_server_socket.bind(("", 8000))
tcp_server_socket.listen(128)
# 创建socket属性
self.tcp_server_socket = tcp_server_socket
@staticmethod
def handle_client_request(new_socket):
rec_data = new_socket.recv(4096)
if len(rec_data) == 0:
new_socket.close()
return
rec_content = rec_data.decode("utf-8")
print(rec_content)
request_list = rec_content.split(" ", 2)
request_path = request_list[1]
print(request_path)
if request_path == '/':
request_path = 'lscd.html'
try:
# 打开文件读取文件中的数据
with open(request_path, "rb") as File: # 用with as 打开文件不用写close()
# 把File 看作对象即可
file_data = File.read()
except Exception as a:
# 打开文件发生异常 返回404
response_line = "HTTP/1.1 404 Error \r\n"
# 响应头
response_header = "Server: szw/1.1 \r\n"
# 空行
# 响应体
with open("erroe.html", "rb") as File: # 用with as 打开文件不用写close()
# 把File 看作对象即可
fd = File.read()
response = response_line + response_header + "\r\n"
response_data2 = response.encode("utf-8") + fd
new_socket.send(response_data2)
else:
# 没有异常显示 200 OK
# 把数据进行按照http协议 响应报文 进行封装再次发送
# http response 报文格式: # 响应行
response_line = "HTTP/1.1 200 OK \r\n"
# 响应头
response_header = "Server: szw/1.1 \r\n"
# 空行
# 响应体
response = response_line + response_header + "\r\n"
response_data = response.encode("utf-8") + file_data
new_socket.send(response_data)
finally:
new_socket.close()
def start(self):
while True:
result = self.tcp_server_socket.accept()
new_socket = result[0]
ip_info = result[1]
sub_threading = threading.Thread(target=self.handle_client_request, args=(new_socket,))
# 设置主线程守护;主线程退出,子线程也接着退出。
sub_threading.setDaemon(True)
sub_threading.start()
if __name__ == '__main__':
web_sever = HttpWebServer()
web_sever.start()