我的静态 Web 服务器演示在 python 中使用 gevent 存在一些问题。当我的浏览器使用http://localhost:8080访问我的 Web 服务器时,它没有任何响应。如果我的静态 Web 服务器演示不使用 gevent,它运作良好,一定是 gevent 有问题。
#coding=utf-8
from socket import *
from gevent import monkey
import re
import gevent
monkey.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()
largeQ
相关分类