단일 프로세스 단일 스레드 비막힘 방식 구현 http 서버
2449 단어 python_http
#!/usr/bin/python3.5
# -*- coding: utf-8 -*-
# @Time : 18-7-2 6:53
# @Author : "Fengwr"
# @email : [email protected]
# @File : http_ _ _ .py
# @Software: PyCharm
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 = "Sorry not found".encode("utf-8")
http_header = "HTTP/1.1 404 NOT FOUND\r
"
http_header += "Content-Length:%d\r
\r
" % len(http_body)
else:
http_body = f.read()
f.close()
http_header = "HTTP/1.1 200 OK\r
"
http_header += "Content-Length:%d\r
\r
" % 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()
새로운 지식점: socket.setbloking(False)#소켓을 막히지 않는 방식으로 설정합니다.Content-Length:%d%len(http_body)#클라이언트가 보낼 바디 내용의 길이를 알려주고 긴 링크를 보냅니다.