# encoding = utf-8
import re
import socket
# 接收消息的方法
def recv_msg(tcp_socket, recv_data):
requests = recv_data.splitlines()
print(requests)
file_name = ""
ret = re.match(r"[^/]+(/[^ ]*)", requests[0])
if ret:
file_name = ret.group(1)
if file_name == "/":
file_name = "templates/index.html"
try:
f = open('report' + file_name, 'rb')
except:
response = "HTTP/1.1 404 Not FOUND\r\n"
response += "\r\n"
response += "<h1>Not found</h1>"
tcp_socket.send(response.encode('utf-8'))
else:
html_content = f.read()
f.close()
response_body = html_content
response_header = "HTTP/1.1 200 OK\r\n"
response_header += "Content-Length: %d\r\n" % len(response_body)
response_header += "\r\n"
response = response_header.encode('utf-8') + response_body
tcp_socket.send(response)
# 主函数
def main():
tcp_socket = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
host = "127.0.0.1"
port = 8081
tcp_socket.bind((host, port))
tcp_socket.listen(128)
tcp_socket.setblocking(False)
client_list = []
while True:
try:
new_client_socket, client_addr = tcp_socket.accept()
except Exception as e:
pass
else:
new_client_socket.setblocking(False)
client_list.append(new_client_socket)
print(str(client_addr))
for client_socket in client_list:
try:
recv_data = client_socket.recv(1024).decode('utf-8')
except Exception as e:
pass
else:
if recv_data:
recv_msg(client_socket, recv_data)
else:
client_list.remove(client_socket)
client_socket.close()
if __name__ == '__main__':
main()
标签:http,socket,tcp,client,recv,response,服务端,name
From: https://www.cnblogs.com/saiya6/p/16936749.html