1. 使用python编写一个静态的web服务器,能够处理静态页面的http请求
原理:
a. 使用socket进行服务端和浏览器之间的通信
b. 使用多线程处理多个客户端浏览器的请求
c. 使用http协议发送响应数据
实现:
# coding:UTF-8 import socket from multiprocessing import Process def handle_request(client_socket): request_data = client_socket.recv(1024) response_first_line = "HTTP/1.1 200 OK\r\n" response_headers = "Server: My Web Static Server\r\n" response_body = "Hello, My Web Static Server" response = response_first_line + response_headers + "\r\n" + response_body client_socket.send(bytes(response, encoding="UTF-8")) client_socket.close() if __name__ == "__main__": server_socket = socket.socket(socket.AF_INET, socket.SOCK_STREAM) server_socket.bind(("",8001)) server_socket.listen(128) while True: client_socket, client_address = server_socket.accept() print(‘["%s", "%s"]用户已经连接上服务器!‘ % client_address) handler = Process(target=handle_request, args=(client_socket,)) handler.start() client_socket.close()
时间: 2024-11-08 17:02:28