@
1.分析
当socket去监听的时候,是堵塞的状态
通过tcp_sever_socket.setblocking(False)去设置不堵塞
当socket发现没有用户的时候会出错,执行异常
当连接上用户的时候会马上把用户发到socket列表中
再遍历socket列表时候也设置,new的socket为非阻塞状态
通过和上面一样的方式
2.代码
import socket
import re
def http_sever(new_socket, recv_data):
recv_data_list = recv_data.splitlines()
ret = re.match(r"[^/]+(/[^ ]*)", recv_data_list[0])
file_name = ""
if ret:
file_name = ret.group(1)
if file_name == "/":
file_name = "/index.html"
http_header = ""
http_body = ""
try:
f = open("./html" + file_name, "rb")
except:
http_body = "<h1>Sorry not found</h1>".encode("utf-8")
http_header = "HTTP/1.1 404 NOT FOUND\r\n"
http_header += "Content-Length:%d\r\n\r\n" % len(http_body)
else:
http_body = f.read()
f.close()
http_header = "HTTP/1.1 200 OK\r\n"
http_header += "Content-Length:%d\r\n\r\n" % len(http_body)
new_socket.send(http_header.encode("utf-8"))
new_socket.send(http_body)
def main():
tcp_sever_socket = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
tcp_sever_socket.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR, 1)
tcp_sever_socket.bind(("", 7890))
tcp_sever_socket.listen(128)
# 设置非堵塞
tcp_sever_socket.setblocking(False)
client_lists = list()
while True:
try:
new_socket, new_add = tcp_sever_socket.accept()
except Exception as ret:
pass
else:
# 设置非堵塞
new_socket.setblocking(False)
client_lists.append(new_socket)
for client_socket in client_lists:
try:
# 尝试接收数据
recv_data = client_socket.recv(1024).decode("utf-8")
except Exception as f:
# 如果没有数据
pass
else:
# 如果有数据有两种情况,1,客户端发来了数据,2客服端下线
if recv_data:
http_sever(client_socket, recv_data)
else:
client_socket.close()
client_lists.remove(client_socket)
tcp_sever_socket.close()
if __name__ == '__main__':
main()
关于作者
个人博客网站
个人GitHub地址
个人公众号: