import socket
import threading
import os
class WebServer:
def __init__(self, port=80, document_root='.'):
self.port = port
self.document_root = document_root
def start(self):
server_socket = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
server_socket.bind(('127.0.0.1', self.port))
server_socket.listen(5)
print('WebServer started at 127.0.0.1:%d' % self.port)
while True:
client_sock, client_address = server_socket.accept()
print('Received connection from', client_address)
# 开启一个新的线程来处理客户端请求。
client_thread = threading.Thread(target=self.handle_client, args=(client_sock,))
client_thread.start()
def handle_client(self, client_sock):
request_data = client_sock.recv(1024)
request_lines = request_data.split(b'\r\n')
request_line = request_lines[0]
request_method, request_uri, request_http_version = request_line.split()
#从请求URI获取文件路径
file_path = os.path.join(self.document_root, request_uri[1:])
#检查文件是否存在
if os.path.exists(file_path) and os.path.isfile(file_path):
#发送一个包含内容类型和长度信息的响应头部。
content_length = os.path.getsize(file_path)
response_header = b'HTTP/1.1 200 OK\r\nContent-Type: text/html\r\nContent-Length: %d\r\n\r\n' % content_length
client_sock.sendall(response_header)
#发送文件内容
with open(file_path, 'rb') as f:
while True:
data = f.read(1024)
if not data:
break
client_sock.sendall(data)
else:
#文件未找到,发送404响应
response_header = b'HTTP/1.1 404 Not Found\r\nContent-Type: text/html\r\n\r\n'
response_body = b'<html><body><h1>404 Not Found</h1></body></html>'
client_sock.sendall(response_header + response_body)
client_sock.close()
#使用示例:
if __name__ == '__main__':
server = WebServer(port=8080, document_root='.')
server.start()
该web服务器支持多线程处理客户端请求,处理静态HTML/CSS/JS等资源。您可以修改document_root变量,将其指向您的web资源目录。
在start方法中,我们首先创建一个socket,并指定IP和端口号。然后通过listen方法开始监听客户端连接。当有客户端连接进来时,我们使用accept方法获取客户端的socket对象和地址,然后创建一个新的线程去处理连接。
在handle_client方法中,我们首先获取客户端发送过来的请求报文的每行,并解析出请求方法、请求URI和HTTP版本。然后根据请求URI构造出本地文件路径,如果文件存在,我们就读取文件,并将其发送给客户端。否则,我们会发送一个404响应给客户端。
以上就是一个简单的Python面向对象版多线程静态web服务器的代码。当然,为了实现完整的HTTP协议,我们还可以进一步完善这个服务器,例如支持GET/POST方法、支持cookies、支持动态网页等。