import socket
import re
import gevent
from gevent import monkey
monkey.patch_all()
class HttpServer(object):
def __init__(self):
server_socket = socket.socket(socket.AF_INET,socket.SOCK_STREAM)
server_socket.setsockopt(socket.SOL_SOCKET,socket.SO_REUSEADDR,1)
server_socket.bind(('',80))
server_socket.listen(128)
self.server_socket = server_socket
def client_handler(self,client_socket):
client_data = client_socket.recv(1024)
print(client_data.decode())
request_path = re.match("GET\s(?P<path>\S+)",client_data.decode())
if request_path :
path = request_path.group('path')
print("客户端请求的路径:" + path)
try:
response_line = "HTTP/1.1 200 OK\r\n"
response_header = "Server: PWS 1.0\r\nContent-Type: text/html;charset=utf8\r\n"
if path == "/":
path = "/index.html"
with open("./html" + path, "rb") as f:
response_content = f.read()
response_data = (response_line + response_header + "\r\n").encode() + response_content
except Exception as e:
response_line = "HTTP/1.1 404\r\n"
response_header = "Server: PWS 1.0\r\nContent-Type: text/html;charset=utf8\r\n"
response_content = "你访问的资源不存在"
response_data = (response_line + response_header + "\r\n" + response_content).encode()
finally:
client_socket.send(response_data)
client_socket.close()
else:
response_line = "HTTP/1.1 403 \r\n"
response_header = "Server: PWS 1.0\r\nContent-Type: text/html;\r\n"
response_content = "<h1>路径错误</h1>\r\n"
response_data = (response_line + response_header + "\r\n" + response_content).encode()
print("客户端请求的路径错误")
client_socket.send(response_data)
client_socket.close()
def start(self):
while 1:
client_socket,client_adder = self.server_socket.accept()
print("接收到一个来自%s的请求"%str(client_adder))
gevent.spawn(self.client_handler, client_socket )
#self.client_handler(client_socket)
def main():
http_server = HttpServer()
http_server.start()
if __name__ == "__main__":
main()