import re
import socket
import select
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 += "
Not found
"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)
epl = select.epoll()
epl.register(tcp_socket.fileno(), select.EPOLLIN)
fd_event_dict = dict()
while True:
fd_event_list = epl.poll()
for fd, event in fd_event_list:
if fd == tcp_socket.fileno():
new_client_socket, client_addr = tcp_socket.accept()
epl.register(new_client_socket.fileno(), select.EPOLLIN)
fd_event_dict[new_client_socket.fileno()] = new_client_socket
elif event == select.EPOLLIN:
recv_data = fd_event_dict[fd].recv(1024).decode('utf-8')
if recv_data:
recv_msg(fd_event_dict[fd], recv_data)
else:
fd_event_dict[fd].close()
epl.unregister(fd)
del fd_event_dict[fd]
if name == 'main':
main()