python写一个http服务器
1 import socket 2 import re 3 4 5 def main(): 6 # 1. 创建socket 7 http_server_socket = socket.socket(socket.AF_INET, socket.SOCK_STREAM) 8 9 # 2. 绑定地址 10 http_server_socket.bind(('', 7890)) 11 12 # 3. 监听 13 http_server_socket.listen(128) 14 15 while True: 16 # 4. 等待客户端连接accept 17 new_http_socket, client_address = http_server_socket.accept() 18 19 # 5. 接收浏览器发送过来的请求 20 request = new_http_socket.recv(1024) 21 22 # 如果request为空,说明客户端关闭socket 23 if request: 24 request = str(request, 'utf8') 25 26 # 请求头请求体按行拆分 27 request_first_line = request.split('\r\n')[0] 28 29 # 'GET /index.html HTTP/1.1' 30 # 从请求头里解析出url地址/index.html 31 request_file_name = re.findall(r'/[^ ]*', request_first_line) 32 print('接到的请求',request) 33 print('寻找请求头里的url',request_file_name) 34 request_file_name = request_file_name[0] 35 print('客户端请求文件地址:', request_file_name) 36 37 # 如果ip后面没有url 38 if request_file_name == '/': 39 request_file_name = '/index.html' 40 41 42 # 在服务器寻找浏览器请求的文件 43 # 6. 返回http格式数据 44 45 try: 46 f = open('.'+request_file_name,'r') 47 except Exception: 48 response_header = "HTTP/1.1 404 NOT FOUND\r\n" #\r\n是为了兼容windows的换行 49 response_empty_line = "\r\n" #加一个空行 50 response_body = 'File not found' 51 else: 52 53 response_header = "HTTP/1.1 200 OK\r\n" #\r\n是为了兼容windows的换行 54 response_empty_line = "\r\n" #加一个空行 55 response_body = f.read() 56 print(response_body) 57 print(type(response_body)) 58 f.close() 59 60 # 拼接响应信息:响应头+空行+响应体 61 response = ''.join([response_header,response_empty_line,response_body]) 62 response = bytes(response, 'utf8') 63 64 new_http_socket.send(response) 65 66 # 7. 关闭 67 else: 68 new_http_socket.close() 69 print('服务结束') 70 71 72 if __name__ == "__main__": 73 main()
在浏览器输入http://127.0.0.1:7890/index.html即可看到index页面
转自https://blog.csdn.net/weixin_38892128/article/details/103113589 感谢