Python socketserver.BaseRequestHandler() Examples

The following are 17 code examples of socketserver.BaseRequestHandler(). You can vote up the ones you like or vote down the ones you don't like, and go to the original project or source file by following the links above each example. You may also want to check out all available functions/classes of the module socketserver , or try the search function .
Example #1
Source File: multi_socketserver_server.py    From blogs with Apache License 2.0 6 votes vote down vote up
def handle(self):
        # 创建一个链接,继承于socketserver中的BaseRequestHandler类
        conn = self.request
        conn.sendall(bytes("Welcome to login...", encoding="utf-8"))
        print("Client connect...")
        while True:
            # 输出等待客户端发送内容
            print("Waitting for recving message...")
            # 接收客户端发送过来的内容
            message = conn.recv(1024)
            # 输出用户发送过来的内容
            print(message.decode('utf-8'))
            # 如果用户输入的是q
            if message == "exit":
                break
            # 给客户端发送内容
            data = input("Reply message:")
            conn.sendall(data.encode('utf-8')) 
Example #2
Source File: test_graphite_bridge.py    From client_python with Apache License 2.0 6 votes vote down vote up
def setUp(self):
        self.registry = CollectorRegistry()

        self.data = ''

        class TCPHandler(SocketServer.BaseRequestHandler):
            def handle(s):
                self.data = s.request.recv(1024)

        server = SocketServer.TCPServer(('', 0), TCPHandler)

        class ServingThread(threading.Thread):
            def run(self):
                server.handle_request()
                server.socket.close()

        self.t = ServingThread()
        self.t.start()

        # Explicitly use localhost as the target host, since connecting to 0.0.0.0 fails on Windows
        address = ('localhost', server.server_address[1])
        self.gb = GraphiteBridge(address, self.registry, _timer=fake_timer) 
Example #3
Source File: network.py    From pycraft with GNU General Public License v2.0 6 votes vote down vote up
def requestHandlerFactory(data_handler):
    class ThreadedTCPRequestHandler(socketserver.BaseRequestHandler):
        def __init__(self, *args):
            self.data_handler = data_handler
            super().__init__(*args)

        def handle(self):
            while True:
                data = receive(self.request)

                if data:
                    response = self.data_handler(self.request, data)

                    if response:
                        send(self.request, response)
                else:
                    break

            log('Handler Exiting')

    return ThreadedTCPRequestHandler 
Example #4
Source File: ssh_forward.py    From king-phisher with BSD 3-Clause "New" or "Revised" License 5 votes vote down vote up
def __init__(self, *args, **kwargs):
		self.server = args[2]
		self.chain_host = self.server.remote_server[0]
		self.chain_port = self.server.remote_server[1]
		self.ssh_transport = self.server.ssh_transport
		socketserver.BaseRequestHandler.__init__(self, *args, **kwargs) 
Example #5
Source File: server.py    From alertR with GNU Affero General Public License v3.0 5 votes vote down vote up
def __init__(self,
                 globalData: GlobalData,
                 serverAddress: Tuple[str, int],
                 RequestHandlerClass: Type[socketserver.BaseRequestHandler]):

        # get reference to global data object
        self.globalData = globalData

        socketserver.TCPServer.__init__(self,
                                        serverAddress,
                                        RequestHandlerClass)


# this class is used for incoming client connections 
Example #6
Source File: server.py    From alertR with GNU Affero General Public License v3.0 5 votes vote down vote up
def __init__(self,
                 request: socket,
                 clientAddress: str,
                 server: ThreadedUnixStreamServer):

        # file nme of this file (used for logging)
        self.fileName = os.path.basename(__file__)

        # get reference to global data object
        self.globalData = server.globalData
        self.serverComm = self.globalData.serverComm

        socketserver.BaseRequestHandler.__init__(self, request, clientAddress, server) 
Example #7
Source File: server.py    From alertR with GNU Affero General Public License v3.0 5 votes vote down vote up
def __init__(self, globalData: GlobalData,
                 serverAddress: str,
                 RequestHandlerClass: socketserver.BaseRequestHandler):

        # get reference to global data object
        self.globalData = globalData

        socketserver.TCPServer.__init__(self,
                                        serverAddress,
                                        RequestHandlerClass)


# this class is used for incoming local client connections (i.e., web page) 
Example #8
Source File: socksserver.py    From CVE-2019-1040 with MIT License 5 votes vote down vote up
def __init__(self, request, client_address, server):
        self.__socksServer = server
        self.__ip, self.__port = client_address
        self.__connSocket= request
        self.__socksVersion = 5
        self.targetHost = None
        self.targetPort = None
        self.__NBSession= None
        socketserver.BaseRequestHandler.__init__(self, request, client_address, server) 
Example #9
Source File: rpc.py    From Project-New-Reign---Nemesis-Main with GNU General Public License v3.0 5 votes vote down vote up
def __init__(self, sock, addr, svr):
        svr.current_handler = self ## cgt xxx
        SocketIO.__init__(self, sock)
        socketserver.BaseRequestHandler.__init__(self, sock, addr, svr) 
Example #10
Source File: conftest.py    From libnl with GNU Lesser General Public License v2.1 5 votes vote down vote up
def tcp_server(request):
    """Start a TCP server in a thread."""
    data = list()

    class Getter(object):
        def __init__(self, t, s, d):
            self.thread = t
            self.server = s
            self._data = d

        @property
        def data(self):
            for i in range(50):
                if self._data:
                    break
                time.sleep(0.1)
            return self._data

    class TCPHandler(socketserver.BaseRequestHandler):
        def handle(self):
            data.append(self.request.recv(25))

    server = socketserver.TCPServer(('', 0), TCPHandler)
    thread = threading.Thread(target=server.serve_forever)
    thread.daemon = True
    thread.start()

    def fin():
        server.socket.close()
        server.shutdown()
        for _ in range(5):
            if not thread.is_alive():
                break
            time.sleep(0.2)
        assert not thread.is_alive()
    request.addfinalizer(fin)

    return Getter(thread, server, data) 
Example #11
Source File: socksserver.py    From Slackor with GNU General Public License v3.0 5 votes vote down vote up
def __init__(self, request, client_address, server):
        self.__socksServer = server
        self.__ip, self.__port = client_address
        self.__connSocket= request
        self.__socksVersion = 5
        self.targetHost = None
        self.targetPort = None
        self.__NBSession= None
        socketserver.BaseRequestHandler.__init__(self, request, client_address, server) 
Example #12
Source File: service.py    From on-pwning with MIT License 5 votes vote down vote up
def __init__(self, request, client_address, server):
        socketserver.BaseRequestHandler.__init__(self, request, client_address, server) 
Example #13
Source File: rpc.py    From ironpython3 with Apache License 2.0 5 votes vote down vote up
def __init__(self, sock, addr, svr):
        svr.current_handler = self ## cgt xxx
        SocketIO.__init__(self, sock)
        socketserver.BaseRequestHandler.__init__(self, sock, addr, svr) 
Example #14
Source File: monserver.py    From clonedigger with GNU General Public License v3.0 5 votes vote down vote up
def __init__(self, request, clientaddress, server ):
        self.locals = {}
        self.globals = globals().copy()
        self.wfile = request.makefile("w")
        self.rfile = request.makefile("r")
        socketserver.BaseRequestHandler.__init__(self, request, clientaddress,
                                                 server ) 
Example #15
Source File: rpc.py    From Fluid-Designer with GNU General Public License v3.0 5 votes vote down vote up
def __init__(self, sock, addr, svr):
        svr.current_handler = self ## cgt xxx
        SocketIO.__init__(self, sock)
        socketserver.BaseRequestHandler.__init__(self, sock, addr, svr) 
Example #16
Source File: test_supervisor_logging.py    From supervisor-logging with Apache License 2.0 4 votes vote down vote up
def test_logging(self):
        """
        Test logging.
        """

        messages = []

        class SyslogHandler(socketserver.BaseRequestHandler):
            """
            Save received messages.
            """

            def handle(self):
                messages.append(self.request[0].strip().decode())

        syslog = socketserver.UDPServer(('0.0.0.0', 0), SyslogHandler)
        try:
            threading.Thread(target=syslog.serve_forever).start()

            env = os.environ.copy()
            env['SYSLOG_SERVER'] = syslog.server_address[0]
            env['SYSLOG_PORT'] = str(syslog.server_address[1])
            env['SYSLOG_PROTO'] = 'udp'

            mydir = os.path.dirname(__file__)

            supervisor = subprocess.Popen(
                ['supervisord', '-c', os.path.join(mydir, 'supervisord.conf')],
                env=env,
            )
            try:

                sleep(3)

                pid = subprocess.check_output(
                    ['supervisorctl', 'pid', 'messages']
                ).decode().strip()

                sleep(8)

                self.assertEqual(
                    list(map(strip_volatile, messages)),
                    ['<14>DATE HOST messages[{pid}]: Test {i} \n\x00'.format(
                        pid=pid,
                        i=i)
                     for i in range(4)]
                )
            finally:
                supervisor.terminate()

        finally:
            syslog.shutdown() 
Example #17
Source File: server.py    From alertR with GNU Affero General Public License v3.0 4 votes vote down vote up
def __init__(self,
                 request: socket,
                 clientAddress: Tuple[str, int],
                 server: ThreadedTCPServer):

        # file nme of this file (used for logging)
        self.fileName = os.path.basename(__file__)

        # ssl socket
        self.sslSocket = None
        self.sslContext = None

        # instance of the client communication object
        self.clientComm = None

        # get client ip address and port
        self.clientAddress = clientAddress[0]
        self.clientPort = clientAddress[1]

        # Get reference to global data object.
        self.globalData = server.globalData
        self.logger = self.globalData.logger

        # get server certificate/key file
        self.serverCertFile = self.globalData.serverCertFile
        self.serverKeyFile = self.globalData.serverKeyFile

        # get client certificate settings
        self.useClientCertificates = self.globalData.useClientCertificates
        self.clientCAFile = self.globalData.clientCAFile

        # Get TLS/SSL setting.
        self.sslProtocol = self.globalData.sslProtocol
        self.sslCiphers = self.globalData.sslCiphers
        self.sslOptions = self.globalData.sslOptions

        # add own server session to the global list of server sessions
        self.serverSessions = self.globalData.serverSessions
        self.serverSessions.append(self)

        # Get reference to the connection watchdog object
        # to inform it about disconnects.
        self.connectionWatchdog = self.globalData.connectionWatchdog

        socketserver.BaseRequestHandler.__init__(self,
                                                 request,
                                                 clientAddress,
                                                 server)