1 短连接
HTTP/1.0 及以前的版本采用的都是短连接
2 长连接
HTTP/1.1 采用的都是长连接
不用gevent, 实现单进程,单线程,长连接,且能并发处理多个浏览器请求的http服务器
核心原理:new_socket.setblocking(False)把套接字设为非阻塞
from socket import *
import re
def serve_client(client_socket, request):
request_lines = request.splitlines()
print(request_lines)
file_name = ""
ret = re.match(r"[^/]+(/[^ ]*)", request_lines[0])
if ret:
file_name = ret.group(1)
if file_name == "/":
file_name = "/index.html"
try:
f = open("./html"+file_name, "rb")
except:
response = "HTTP/1.1 404 NOT FOUND\n\n"
response += "-----file not fonund-----"
client_socket.send(response.encode("utf-8"))
else:
response_body = f.read()
f.close()
response_header = "HTTP/1.1 200 OK\n"
response_header += "Content-Length:{}\n".format(len(response_body))
response_header += "\n"
response = response_header.encode("utf-8") + response_body
client_socket.send(response)
if __name__ == "__main__":
tcp_socket = socket(AF_INET, SOCK_STREAM)
tcp_socket.setsockopt(SOL_SOCKET, SO_REUSEADDR, 1)
tcp_socket.bind(("", 7890))
tcp_socket.listen(128)
tcp_socket.setblocking(False)
client_socket_list = list()
while True:
try:
new_socket, client_addr = tcp_socket.accept()
except Exception as e:
pass
else:
new_socket.setblocking(False)
client_socket_list.append(new_socket)
for client_socket in client_socket_list:
try:
recv_data = client_socket.recv(1024).decode("utf-8")
except Exception as e:
pass
else:
if recv_data:
serve_client(client_socket, recv_data)
else:
client_socket.close()
client_socket_list.remove(client_socket)
tcp_socket.close()