Python socketserver.TCPServer() Examples

The following are 30 code examples of socketserver.TCPServer(). 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: module_utils.py    From QRLJacking with GNU General Public License v3.0 9 votes vote down vote up
def start_serving(self,host="0.0.0.0"):
        serve_dir = os.path.join(Settings.path,"core","www",self.name)
        f = open( os.path.join(serve_dir,"index.html"),"w")
        f.write(self.html)
        f.close()
        class ReusableTCPServer(socketserver.TCPServer):
            allow_reuse_address = True
            logging = False
        class MyHandler(http.server.SimpleHTTPRequestHandler):
            def __init__(self, *args, **kwargs):
                super().__init__(*args, directory=serve_dir, **kwargs)
            def log_message(self, format, *args):
                if self.server.logging:
                    http.server.SimpleHTTPRequestHandler.log_message(self, format, *args)

        self.httpd = ReusableTCPServer( (host, self.port), MyHandler)
        t = thread.start_new_thread(self.httpd.serve_forever, ()) 
Example #2
Source File: cb_tools.py    From Forager with MIT License 7 votes vote down vote up
def run_feed_server():
    #stands up the feed server, points to the CB/json_feeds dir
    chdir('data/json_feeds/')
    port = 8000
    handler = http.server.SimpleHTTPRequestHandler
    httpd = socketserver.TCPServer(("", port), handler)

    try:
        print((Fore.GREEN + '\n[+]' + Fore.RESET), end=' ')
        print(('Feed Server listening at http://%s:8000' % gethostname()))
        httpd.serve_forever()
    except:
        print((Fore.RED + '\n[-]' + Fore.RESET), end=' ')
        print("Server exited")

    return 
Example #3
Source File: test_socketserver.py    From ironpython3 with Apache License 2.0 6 votes vote down vote up
def test_shutdown(self):
        # Issue #2302: shutdown() should always succeed in making an
        # other thread leave serve_forever().
        class MyServer(socketserver.TCPServer):
            pass

        class MyHandler(socketserver.StreamRequestHandler):
            pass

        threads = []
        for i in range(20):
            s = MyServer((HOST, 0), MyHandler)
            t = threading.Thread(
                name='MyServer serving',
                target=s.serve_forever,
                kwargs={'poll_interval':0.01})
            t.daemon = True  # In case this function raises.
            threads.append((t, s))
        for t, s in threads:
            t.start()
            s.shutdown()
        for t, s in threads:
            t.join()
            s.server_close() 
Example #4
Source File: test_socketserver.py    From Fluid-Designer with GNU General Public License v3.0 6 votes vote down vote up
def test_shutdown(self):
        # Issue #2302: shutdown() should always succeed in making an
        # other thread leave serve_forever().
        class MyServer(socketserver.TCPServer):
            pass

        class MyHandler(socketserver.StreamRequestHandler):
            pass

        threads = []
        for i in range(20):
            s = MyServer((HOST, 0), MyHandler)
            t = threading.Thread(
                name='MyServer serving',
                target=s.serve_forever,
                kwargs={'poll_interval':0.01})
            t.daemon = True  # In case this function raises.
            threads.append((t, s))
        for t, s in threads:
            t.start()
            s.shutdown()
        for t, s in threads:
            t.join()
            s.server_close() 
Example #5
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 #6
Source File: server.py    From Turing with MIT License 6 votes vote down vote up
def __init__(self, args=None):
        """
        :param args: Argument parser args. If None, the server will setup and
            use its own argument parser (using
            :meth:`pyqode.core.backend.default_parser`)
        """
        self.reset_heartbeat()
        if not args:
            args = default_parser().parse_args()
        self.port = args.port
        self.timeout = HEARTBEAT_DELAY
        self._Handler.srv = self
        socketserver.TCPServer.__init__(
            self, ('127.0.0.1', int(args.port)), self._Handler)
        print('started on 127.0.0.1:%d' % int(args.port))
        print('running with python %d.%d.%d' % (sys.version_info[:3]))
        self._heartbeat_thread = threading.Thread(target=self.heartbeat)
        self._heartbeat_thread.setDaemon(True)
        self._heartbeat_thread.start() 
Example #7
Source File: editor.py    From DeTTECT with GNU General Public License v3.0 6 votes vote down vote up
def _run_webserver(self):
        """
        Starts the webserver on the given port.
        """
        try:
            os.chdir('./editor/dist')
            self.httpd = TCPServer(('', self.port), QuietHTTPRequestHandler)

            print("Editor started at port %d" % self.port)
            url = 'http://localhost:%d/dettect-editor' % self.port

            if not os.getenv('DeTTECT_DOCKER_CONTAINER'):
                print("Opening webbrowser: " + url)
                webbrowser.open_new_tab(url)
            else:
                print("You can open the Editor on: " + url)

            self.httpd.serve_forever()
        except Exception as e:
            print("Could not start webserver: " + str(e)) 
Example #8
Source File: rpc.py    From Fluid-Designer with GNU General Public License v3.0 6 votes vote down vote up
def handle_error(self, request, client_address):
        """Override TCPServer method

        Error message goes to __stderr__.  No error message if exiting
        normally or socket raised EOF.  Other exceptions not handled in
        server code will cause os._exit.

        """
        try:
            raise
        except SystemExit:
            raise
        except:
            erf = sys.__stderr__
            print('\n' + '-'*40, file=erf)
            print('Unhandled server exception!', file=erf)
            print('Thread: %s' % threading.current_thread().name, file=erf)
            print('Client Address: ', client_address, file=erf)
            print('Request: ', repr(request), file=erf)
            traceback.print_exc(file=erf)
            print('\n*** Unrecoverable, server exiting!', file=erf)
            print('-'*40, file=erf)
            os._exit(0)

#----------------- end class RPCServer -------------------- 
Example #9
Source File: jobStoreTest.py    From toil with Apache License 2.0 6 votes vote down vote up
def testImportHttpFile(self):
            '''Test importing a file over HTTP.'''
            http = socketserver.TCPServer(('', 0), StubHttpRequestHandler)
            try:
                httpThread = threading.Thread(target=http.serve_forever)
                httpThread.start()
                try:
                    assignedPort = http.server_address[1]
                    url = 'http://localhost:%d' % assignedPort
                    with self.jobstore_initialized.readFileStream(
                            self.jobstore_initialized.importFile(url)) as readable:
                        f1 = readable.read()
                        f2 = StubHttpRequestHandler.fileContents
                        if isinstance(f1, bytes) and not isinstance(f2, bytes):
                            f1 = f1.decode()
                        if isinstance(f2, bytes) and not isinstance(f1, bytes):
                            f1 = f1.encode()
                        self.assertEqual(f1, f2)
                finally:
                    http.shutdown()
                    httpThread.join()
            finally:
                http.server_close() 
Example #10
Source File: websocket.py    From quokka with Mozilla Public License 2.0 6 votes vote down vote up
def enqueue_lines(self):
        run = True
        line_queue = self.line_queue

        class WebSocketHandler(websocket.BaseWebSocketHandler):
            def on_message(self, message):
                line_queue.put(message)

            def should_close(self):
                return not run

        class _TCPServer(TCPServer):
            allow_reuse_address = True

        self.server = _TCPServer(self.addr_port, WebSocketHandler)
        try:
            self.server.serve_forever()
        finally:
            run = False 
Example #11
Source File: wsdd.py    From wsdd with MIT License 6 votes vote down vote up
def __init__(self, selector, listen_address, clients, known_devices):
        self.clients = clients

        if isinstance(listen_address, int) or listen_address.isnumeric():
            s_addr = ('localhost', int(listen_address))
            socketserver.TCPServer.allow_reuse_address = True
            s = socketserver.TCPServer(s_addr, ApiRequestHandler)
        else:
            s = socketserver.UnixStreamServer(
                listen_address, ApiRequestHandler)

        # quiet hacky
        s.wsd_clients = clients
        s.wsd_known_devices = known_devices

        selector.register(s.fileno(), selectors.EVENT_READ, s) 
Example #12
Source File: rpc.py    From ironpython3 with Apache License 2.0 6 votes vote down vote up
def handle_error(self, request, client_address):
        """Override TCPServer method

        Error message goes to __stderr__.  No error message if exiting
        normally or socket raised EOF.  Other exceptions not handled in
        server code will cause os._exit.

        """
        try:
            raise
        except SystemExit:
            raise
        except:
            erf = sys.__stderr__
            print('\n' + '-'*40, file=erf)
            print('Unhandled server exception!', file=erf)
            print('Thread: %s' % threading.current_thread().name, file=erf)
            print('Client Address: ', client_address, file=erf)
            print('Request: ', repr(request), file=erf)
            traceback.print_exc(file=erf)
            print('\n*** Unrecoverable, server exiting!', file=erf)
            print('-'*40, file=erf)
            os._exit(0)

#----------------- end class RPCServer -------------------- 
Example #13
Source File: test_socketserver.py    From Project-New-Reign---Nemesis-Main with GNU General Public License v3.0 6 votes vote down vote up
def test_shutdown(self):
        # Issue #2302: shutdown() should always succeed in making an
        # other thread leave serve_forever().
        class MyServer(socketserver.TCPServer):
            pass

        class MyHandler(socketserver.StreamRequestHandler):
            pass

        threads = []
        for i in range(20):
            s = MyServer((HOST, 0), MyHandler)
            t = threading.Thread(
                name='MyServer serving',
                target=s.serve_forever,
                kwargs={'poll_interval':0.01})
            t.daemon = True  # In case this function raises.
            threads.append((t, s))
        for t, s in threads:
            t.start()
            s.shutdown()
        for t, s in threads:
            t.join()
            s.server_close() 
Example #14
Source File: rpc.py    From ironpython3 with Apache License 2.0 5 votes vote down vote up
def server_bind(self):
        "Override TCPServer method, no bind() phase for connecting entity"
        pass 
Example #15
Source File: rpc.py    From Project-New-Reign---Nemesis-Main with GNU General Public License v3.0 5 votes vote down vote up
def server_bind(self):
        "Override TCPServer method, no bind() phase for connecting entity"
        pass 
Example #16
Source File: test_socketserver.py    From Project-New-Reign---Nemesis-Main with GNU General Public License v3.0 5 votes vote down vote up
def test_TCPServer(self):
        self.run_server(socketserver.TCPServer,
                        socketserver.StreamRequestHandler,
                        self.stream_examine) 
Example #17
Source File: server.py    From Project-New-Reign---Nemesis-Main with GNU General Public License v3.0 5 votes vote down vote up
def __init__(self, addr, requestHandler=SimpleXMLRPCRequestHandler,
                 logRequests=True, allow_none=False, encoding=None,
                 bind_and_activate=True, use_builtin_types=False):
        self.logRequests = logRequests

        SimpleXMLRPCDispatcher.__init__(self, allow_none, encoding, use_builtin_types)
        socketserver.TCPServer.__init__(self, addr, requestHandler, bind_and_activate) 
Example #18
Source File: server.py    From Project-New-Reign---Nemesis-Main with GNU General Public License v3.0 5 votes vote down vote up
def server_bind(self):
        """Override server_bind to store the server name."""
        socketserver.TCPServer.server_bind(self)
        host, port = self.socket.getsockname()[:2]
        self.server_name = socket.getfqdn(host)
        self.server_port = port 
Example #19
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 #20
Source File: test_socketserver.py    From Project-New-Reign---Nemesis-Main with GNU General Public License v3.0 5 votes vote down vote up
def test_tcpserver_bind_leak(self):
        # Issue #22435: the server socket wouldn't be closed if bind()/listen()
        # failed.
        # Create many servers for which bind() will fail, to see if this result
        # in FD exhaustion.
        for i in range(1024):
            with self.assertRaises(OverflowError):
                socketserver.TCPServer((HOST, -1),
                                       socketserver.StreamRequestHandler) 
Example #21
Source File: serve.py    From pyodide with Mozilla Public License 2.0 5 votes vote down vote up
def server(port):
    httpd = socketserver.TCPServer(("", port), Handler)
    return httpd 
Example #22
Source File: test_sources.py    From osbuild with Apache License 2.0 5 votes vote down vote up
def runFileServer(barrier, directory):
    class Handler(http.server.SimpleHTTPRequestHandler):
        def __init__(self, request, client_address, server):
            super().__init__(request, client_address, server, directory=directory)

    httpd = socketserver.TCPServer(('', 80), Handler)
    barrier.wait()
    httpd.serve_forever() 
Example #23
Source File: rpc.py    From ironpython3 with Apache License 2.0 5 votes vote down vote up
def __init__(self, addr, handlerclass=None):
        if handlerclass is None:
            handlerclass = RPCHandler
        socketserver.TCPServer.__init__(self, addr, handlerclass) 
Example #24
Source File: pacemaker.py    From pacemaker with MIT License 5 votes vote down vote up
def __init__(self, args):
        server_address = (args.listen, args.port)
        self.allow_reuse_address = True
        if args.ipv6 or ':' in args.listen:
            self.address_family = socket.AF_INET6
        socketserver.TCPServer.__init__(self, server_address, RequestHandler)
        self.args = args 
Example #25
Source File: server.py    From armory with zlib License 5 votes vote down vote up
def run_tcp():
    Handler = http.server.SimpleHTTPRequestHandler
    try:
        httpd = socketserver.TCPServer(("", 8040), Handler)
        httpd.serve_forever()
    except:
        print('Server already running') 
Example #26
Source File: rpc.py    From ironpython3 with Apache License 2.0 5 votes vote down vote up
def server_activate(self):
        """Override TCPServer method, connect() instead of listen()

        Due to the reversed connection, self.server_address is actually the
        address of the Idle Client to which we are connecting.

        """
        self.socket.connect(self.server_address) 
Example #27
Source File: test_against_stdlib_http.py    From h11 with MIT License 5 votes vote down vote up
def socket_server(handler):
    httpd = socketserver.TCPServer(("127.0.0.1", 0), handler)
    thread = threading.Thread(
        target=httpd.serve_forever, kwargs={"poll_interval": 0.01}
    )
    thread.daemon = True
    try:
        thread.start()
        yield httpd
    finally:
        httpd.shutdown() 
Example #28
Source File: rpc.py    From ironpython3 with Apache License 2.0 5 votes vote down vote up
def get_request(self):
        "Override TCPServer method, return already connected socket"
        return self.socket, self.server_address 
Example #29
Source File: gamestate_listener.py    From GoTimer with BSD 2-Clause "Simplified" License 5 votes vote down vote up
def __init__(self, server_address, req_handler_class, msg_queue):
        self.msg_queue = msg_queue
        self.should_be_running = True
        socketserver.TCPServer.__init__(
            self, server_address, req_handler_class) 
Example #30
Source File: runInIndesign.py    From RunInIndesign with MIT License 5 votes vote down vote up
def __init__(self, server_address, RequestHandlerClass, cons, onExit, bind_and_activate=True):
		self.console=cons
		self.onExit=onExit
		socketserver.TCPServer.__init__(self,server_address,RequestHandlerClass)
		return