面向物件tcp伺服器端
阿新 • • 發佈:2018-11-27
import socket import re def main(): """主函式""" # 封裝 一個函式一個功能 建立伺服器 提取客戶端 處理單獨的客戶端 # tcp_socket = make_server() # accept_client(tcp_socket) tcp_socket = WebServer() tcp_socket.accept_client() class WebServer(object): def __init__(self): """建立伺服器 初始化伺服器屬性"""self.tcp_socket = socket.socket(socket.AF_INET, socket.SOCK_STREAM) self.tcp_socket.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR, 1) self.tcp_socket.bind(('', 1372)) self.tcp_socket.listen(128) # return tcp_socket def accept_client(self): """不斷提取客戶端""" while True: client, addres = self.tcp_socket.accept() self.client_exec(client) # 關閉伺服器 self.tcp_socket.close() def client_exec(self, client): """單獨處理客戶端""" re_data = client.recv(1024).decode() re_lines = re_data.splitlines() print(re_lines[0]) try: re_match = re.match(r'[^/]+(/[^ ]*)', re_lines[0]) if re_match: file_name = re_match.group(1) if file_name == '/': file_name = '/index.html' except Exception as e: print(e) try: head = 'HTTP/1.1 200 OK\r\n' with open('./html{}'.format(file_name), 'rb') as file: body = file.read() content = head + '\r\n' client.send(content.encode()) client.send(body) except Exception as e: print(e) head = 'HTTP/1.1 404 NOT FOUND\r\n' body = 'sorry not find' content = head + '\r\n' + body client.send(content.encode()) # 關閉客戶端伺服器 client.close() if __name__ == '__main__': main()