https

import socketserver
import socket
import threading

class TCPHandler(socketserver.BaseRequestHandler):
    def pipe(self,sock_in, sock_out):
        try:
            while True:
                b = sock_in.recv(65536)
                if not b:
                    break
                sock_out.sendall(b)
        except socket.error:
            pass
        finally:
            sock_in.close()
            sock_out.close()


    def connecting(self):
        httpd_sock = socket.socket()
        try:
            httpd_sock.connect(('127.0.0.1', 18443))
        except socket.error:
            self.server.socket.close()
            return

        httpd_sock.setsockopt(socket.IPPROTO_TCP, socket.TCP_NODELAY, 1)
        threading.Thread(target=self.pipe, args=(self.server.socket, httpd_sock)).start()
        self.pipe(httpd_sock, self.server.socket)


    # 重写handle方法
    def handle(self):
        while True:
            try:
                # self.server.socket.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR, 1)
                self.server.socket.setsockopt(socket.IPPROTO_TCP, socket.TCP_NODELAY, 1) # 关闭Nagle算法,立即发送数据
                self.server.socket.accept()
                self.server.socket.setsockopt(socket.SOL_SOCKET, socket.SO_RCVBUF, 65535)
                self.connecting()

            except ConnectionResetError as e:
                print(self.client_address, e)
                break
if __name__ == '__main__':
    HOST, PORT = '0.0.0.0', 448
    with socketserver.ThreadingTCPServer((HOST, PORT), TCPHandler) as server:
        server.serve_forever()

Last updated