我的静态 Web 服务器演示在 python 中使用 gevent 存在一些问题。当我的浏览器使用http://localhost:8080访问我的 Web 服务器时,它没有任何响应。如果我的静态 Web 服务器演示不使用 gevent,它运作良好,一定是 gevent 有问题。#coding=utf-8from socket import *from gevent import monkeyimport reimport geventmonkey.patch_all()def handle_client(client_socket): recv_data = client_socket.recv(1024).decode("utf-8") response_header_lines = recv_data.splitlines() for line in response_header_lines: print(line) http_request_line = response_header_lines[0] get_file_name = re.match("[^/]+(/[^ ]*)", http_request_line).group(1) print("file name is ===>%s"%get_file_name) #for test if get_file_name == "/": get_file_name = DOCUMENTS_ROOT + "/index.html" else: get_file_name = DOCUMENTS_ROOT + get_file_name print("file name is ===2>%s"%get_file_name) try: f = open(get_file_name, "rb") except IOError: response_header = "HTTP/1.1 404 not found\r\n" response_header += "\r\n" response_body = "404 not found" else: response_header = "HTTP/1.1 200 OK\r\n" response_header += "\r\n" response_body = f.read() f.close() finally: client_socket.send(response_header.encode("utf-8")) client_socket.send(response_body) client_socket.close()def main(): server_socket = socket(AF_INET, SOCK_STREAM) server_socket.setsockopt(SOL_SOCKET, SO_REUSEADDR, 1) server_socket.bind(("", 8080)) server_socket.listen(128) while True: client_socket, client_addr = server_socket.accept() #handle_client(client_socket) gevent.spawn(handle_client, client_socket) server_socket.close()DOCUMENTS_ROOT = "./html"if __name__ == "__main__": main()
1 回答
largeQ
TA贡献2039条经验 获得超7个赞
你应该在导入任何将被修补的模块之前应用猴子补丁,socket这里有问题:
from gevent import monkey
monkey.patch_all()
from socket import *
...
它的文档强调:
补丁应该在程序的生命周期中尽早完成。例如,主模块(针对main进行测试的模块 或第一个导入的模块)应该以此代码开头,最好在任何其他导入之前
添加回答
举报
0/150
提交
取消