Web静态服务器-7-gevent版
from gevent import monkey
import gevent
import socket
import sys
import re
monkey.patch_all()
class WSGIServer(object):
"""定义一个WSGI服务器的类"""
def __init__(self, port, documents_root):
self.server_socket = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
self.server_socket.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR, 1)
self.server_socket.bind(("", port))
self.server_socket.listen(128)
self.documents_root = documents_root
def run_forever(self):
"""运行服务器"""
while True:
new_socket, new_addr = self.server_socket.accept()
gevent.spawn(self.deal_with_request, new_socket)
def deal_with_request(self, client_socket):
"""为这个浏览器服务器"""
while True:
request = client_socket.recv(1024).decode('utf-8')
if not request:
new_socket.close()
break
request_lines = request.splitlines()
for i, line in enumerate(request_lines):
print(i, line)
ret = re.match(r"([^/]*)([^ ]+)", request_lines[0])
if ret:
print("正则提取数据:", ret.group(1))
print("正则提取数据:", ret.group(2))
file_name = ret.group(2)
if file_name == "/":
file_name = "/index.html"
file_path_name = self.documents_root + file_name
try:
f = open(file_path_name, "rb")
except:
response_body = "没有你需要的文件......".encode("utf-8")
response_headers = "HTTP/1.1 404 not found\r\n"
response_headers += "Content-Type:text/html;charset=utf-8\r\n"
response_headers += "Content-Length:%d\r\n" % len(response_body)
response_headers += "\r\n"
send_data = response_headers.encode("utf-8") + response_body
client_socket.send(send_data)
else:
content = f.read()
f.close()
response_body = content
response_headers = "HTTP/1.1 200 OK\r\n"
response_headers += "Content-Type:text/html;charset=utf-8\r\n"
response_headers += "Content-Length:%d\r\n" % len(response_body)
response_headers += "\r\n"
send_data = response_headers.encode("utf-8") + response_body
client_socket.send(send_data)
DOCUMENTS_ROOT = "./html"
def main():
"""控制web服务器整体"""
if len(sys.argv) == 2:
port = sys.argv[1]
if port.isdigit():
port = int(port)
else:
print("运行方式如: python3 xxx.py 7890")
return
print("http服务器使用的port:%s" % port)
http_server = WSGIServer(port, DOCUMENTS_ROOT")
http_server.run_forever()
if __name__ == "__main__":
main()