面向對象epoll並發
阿新 • • 發佈:2019-03-31
epoll groups .so resp .html htm 接收 for all
面向對象epoll
# -*- coding: utf-8 -*- import socket import selectors import re class Httpserver: def __init__(self): self.server = socket.socket() self.server.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR, 1) # 釋放端口 self.epoll_selector = selectors.EpollSelector()def bind(self, port): self.server.bind((‘‘, port)) def start(self): self.server.listen(1000)
# 將self.server作為參數傳入 self.server_conn中,所以server_conn得有一個參數來接收 self.epoll_selector.register(self.server, selectors.EVENT_READ, self.server_conn) while True: events= self.epoll_selector.select() for event, n in events: file_obj = event.fileobj callback = event.data callback(file_obj) def server_conn(self, server): conn, addr = server.accept() self.epoll_selector.register(conn, selectors.EVENT_READ, self.server_recv)def server_recv(self, conn): recv_data = conn.recv(1024) if recv_data: response_data_line = recv_data.splitlines()[0] file_path = re.match(r‘\w+ +(/[^ ]*) ‘, response_data_line.decode()).groups()[0] if file_path == ‘/‘: file_path = ‘/index.html‘ file_path = ‘./static‘ + file_path send_html_content = self.read_file(file_path) if not send_html_content: response_head = ‘HTTP/1.1 404 NotFound\r\n‘ send_html_content = ‘This page is not found.‘ else: response_head = ‘HTTP/1.1 200 OK\r\n‘ response_server_version = ‘super: 1.1\r\n‘ send_data = response_head + response_server_version + ‘\r\n‘ + send_html_content conn.send(send_data.encode()) self.epoll_selector.unregister(conn) conn.close() def read_file(self, file_path): try: with open(file_path, ‘rb‘) as f: content = f.read() except Exception: return False return content.decode() if __name__ == ‘__main__‘: server = Httpserver() server.bind(8000) server.start()
面向對象epoll並發