import socket
import threading
def handle(user_socket):
web_recv = user_socket.recv(4096)
if len(web_recv) == 0:
print('放弃连接')
user_socket.close()
return
web_request = web_recv.decode()
index = web_request.split(' ', 2)
request_path = index[1]
if request_path == '/':
request_path = '/index.html'
try:
with open('.' + request_path, mode='rb') as f:
file_data = f.read()
except Exception as e:
print(e)
with open('./error.html', mode='rb') as f:
error_file = f.read()
response_line = 'HTTP/1.1 404 Not Found\r\n'
response_head = 'PWS2023\r\n'
response = ((response_line + response_head + '\r\n').encode()
+ error_file)
user_socket.send(response)
else:
response_line = 'HTTP/1.1 200 OK\r\n'
response_head = 'PWS2023\r\n'
response = ((response_line + response_head + '\r\n').encode()
+ file_data)
user_socket.send(response)
finally:
user_socket.close()
if __name__ == '__main__':
def main():
main_socket = socket.socket(socket.AF_INET,
socket.SOCK_STREAM)
main_socket.bind(('', 8000))
main_socket.listen(128)
while True:
user_socket, ip_port = main_socket.accept()
print(ip_port)
sub_thread = threading.Thread(target=handle,
args=(user_socket,))
sub_thread.setDaemon(True)
sub_thread.start()
main()
Python - 静态web服务-多任务
于 2023-12-24 10:54:20 首次发布