|
| 1 | +# coding:utf-8 |
| 2 | + |
| 3 | +import socket |
| 4 | + |
| 5 | +from xkits import ThreadPool |
| 6 | + |
| 7 | +# TARGET_HOST = "example.com" |
| 8 | +# TARGET_PORT = 80 |
| 9 | +TARGET_HOST = "localhost" |
| 10 | +TARGET_PORT = 9000 |
| 11 | + |
| 12 | + |
| 13 | +class SockRequestHandler(): |
| 14 | + def __init__(self, client_socket: socket.socket): |
| 15 | + self.__client_socket: socket.socket = client_socket |
| 16 | + self.__server_socket: socket.socket = socket.create_connection((TARGET_HOST, TARGET_PORT)) # noqa:E501 |
| 17 | + |
| 18 | + def __del__(self): |
| 19 | + self.server_socket.close() |
| 20 | + self.client_socket.close() |
| 21 | + |
| 22 | + @property |
| 23 | + def server_socket(self) -> socket.socket: |
| 24 | + return self.__server_socket |
| 25 | + |
| 26 | + @property |
| 27 | + def client_socket(self) -> socket.socket: |
| 28 | + return self.__client_socket |
| 29 | + |
| 30 | + def send_to_server(self): |
| 31 | + while (data := self.client_socket.recv(1048576)): |
| 32 | + print(f"send {len(data)} to server") |
| 33 | + self.server_socket.sendall(data) |
| 34 | + # print(data) |
| 35 | + print("send to server end") |
| 36 | + |
| 37 | + def send_to_client(self): |
| 38 | + while (data := self.server_socket.recv(1048576)): |
| 39 | + print(f"send {len(data)} to client") |
| 40 | + self.client_socket.sendall(data) |
| 41 | + # print(data) |
| 42 | + print("send to client end") |
| 43 | + |
| 44 | + def run(self): |
| 45 | + print("socket run") |
| 46 | + tpool: ThreadPool = ThreadPool() |
| 47 | + tpool.submit(self.send_to_server) |
| 48 | + tpool.submit(self.send_to_client) |
| 49 | + for thd in tpool._threads: |
| 50 | + print(f"wait thread {thd}") |
| 51 | + thd.join() |
| 52 | + print("socket end") |
| 53 | + |
| 54 | + |
| 55 | +def listen(host: str, port: int): |
| 56 | + server_socket = socket.socket(socket.AF_INET, socket.SOCK_STREAM) |
| 57 | + server_socket.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR, 1) |
| 58 | + server_socket.bind((host, port)) |
| 59 | + server_socket.listen(5) |
| 60 | + |
| 61 | + print(f"Listening on {host}:{port}") |
| 62 | + |
| 63 | + while True: |
| 64 | + client_socket, _ = server_socket.accept() |
| 65 | + print(f"Client Socket: {client_socket}") |
| 66 | + SockRequestHandler(client_socket).run() |
| 67 | + |
| 68 | + |
| 69 | +if __name__ == "__main__": |
| 70 | + listen("0.0.0.0", 8000) |
0 commit comments