twisted.internet.endpoints.TCP4ServerEndpoint

Here are the examples of the python api twisted.internet.endpoints.TCP4ServerEndpoint taken from open source projects. By voting up you can indicate which examples are most useful and appropriate.

16 Examples 7

3 Source : test_tcp.py
with MIT License
from autofelix

    def server(self, reactor):
        """
        Create a server-side TCP endpoint.
        """
        return TCP4ServerEndpoint(reactor, 0, interface=self.interface)


    def client(self, reactor, serverAddress):

3 Source : iosim.py
with MIT License
from autofelix

def connectableEndpoint(debug=False):
    """
    Create an endpoint that can be fired on demand.

    @param debug: A flag; whether to dump output from the established
        connection to stdout.
    @type debug: L{bool}

    @return: A client endpoint, and an object that will cause one of the
        L{Deferred}s returned by that client endpoint.
    @rtype: 2-L{tuple} of (L{IStreamClientEndpoint}, L{ConnectionCompleter})
    """
    reactor = MemoryReactorClock()
    clientEndpoint = TCP4ClientEndpoint(reactor, "0.0.0.0", 4321)
    serverEndpoint = TCP4ServerEndpoint(reactor, 4321)
    serverEndpoint.listen(Factory.forProtocol(Protocol))
    return clientEndpoint, ConnectionCompleter(reactor)

3 Source : test_options.py
with MIT License
from fbla-competitive-events

    def _endpointTest(self, service):
        """
        Use L{Options} to parse a single service configuration parameter and
        verify that an endpoint of the correct type is added to the list for
        that service.
        """
        options = Options()
        options.parseOptions(['--' + service, 'tcp:1234'])
        self.assertEqual(len(options[service]), 1)
        self.assertIsInstance(
            options[service][0], endpoints.TCP4ServerEndpoint)


    def test_endpointSMTP(self):

3 Source : test_options.py
with MIT License
from fbla-competitive-events

    def test_protoDefaults(self):
        """
        POP3 and SMTP each listen on a TCP4ServerEndpoint by default.
        """
        options = Options()
        options.parseOptions([])

        self.assertEqual(len(options['pop3']), 1)
        self.assertIsInstance(
            options['pop3'][0], endpoints.TCP4ServerEndpoint)

        self.assertEqual(len(options['smtp']), 1)
        self.assertIsInstance(
            options['smtp'][0], endpoints.TCP4ServerEndpoint)


    def test_protoDisable(self):

3 Source : common.py
with MIT License
from magic-wormhole

    def _setup_relay(self, do_listen=False, web_log_requests=False, **kwargs):
        channel_db = create_or_upgrade_channel_db(":memory:")
        self._server = make_server(channel_db, **kwargs)
        if do_listen:
            ep = endpoints.TCP4ServerEndpoint(reactor, 0, interface="127.0.0.1")
            self._site = make_web_server(self._server,
                                         log_requests=web_log_requests)
            self._lp = yield ep.listen(self._site)
            addr = self._lp.getHost()
            self.relayurl = "ws://127.0.0.1:%d/v1" % addr.port
            self.rdv_ws_port = addr.port

    def tearDown(self):

3 Source : base.py
with MIT License
from opacam

    def __init__(self, ui, port, coherence):
        log.LogAble.__init__(self)
        self.site = Site(SimpleRoot(coherence))

        self.endpoint = endpoints.TCP4ServerEndpoint(reactor, port)
        self._endpoint_listen(coherence, port)

    def _endpoint_listen(self, coherence, port):

3 Source : Server.py
with MIT License
from rrennoir

    def __init__(self, tcp_port: int, udp_port: int) -> None:

        self.udp_clients = []
        self.data_queue = DataQueue([], [])

        self.tcp_endpoint = TCP4ServerEndpoint(reactor, tcp_port)
        self.tcp_endpoint.listen(TCP_Factory(self.data_queue))
        reactor.listenUDP(udp_port, UDP_Server(self.udp_clients,
                                               self.data_queue))

    def close(self) -> None:

0 Source : testssl_result_handler.py
with Apache License 2.0
from bitsofinfo

def init_watching(input_dir,
                  config_dir,
                  input_dir_watchdog_threads,
                  input_dir_sleep_seconds,
                  debug_objectpath_expr,
                  input_filename_filter,
                  dump_evaldoc_on_error,
                  debug_dump_evaldoc,
                  httpserver_port,
                  httpserver_root_dir):

    # mthreaded...
    if (isinstance(input_dir_watchdog_threads,str)):
        input_dir_watchdog_threads = int(input_dir_watchdog_threads)

    # create watchdog to look for new config files
    result_handler_config_monitor = HandlerConfigFileMonitor()

    # create watchdog to look for new files
    event_handler = TestsslResultFileMonitor()
    event_handler.set_threads(input_dir_watchdog_threads)
    event_handler.input_dir = input_dir
    event_handler.input_filename_filter = input_filename_filter
    if (isinstance(input_dir_sleep_seconds,str)):
        input_dir_sleep_seconds = int(input_dir_sleep_seconds)
    event_handler.input_dir_sleep_seconds = input_dir_sleep_seconds

    # Create a TestsslProcessor to consume the testssl_cmds files
    event_handler.testssl_result_processor = TestsslResultProcessor()
    event_handler.testssl_result_processor.debug_objectpath_expr = debug_objectpath_expr
    event_handler.testssl_result_processor.dump_evaldoc_on_error = dump_evaldoc_on_error
    event_handler.testssl_result_processor.debug_dump_evaldoc = debug_dump_evaldoc

    # give the processor the total number of threads to use
    # for processing testssl.sh cmds concurrently
    if (isinstance(input_dir_watchdog_threads,str)):
        input_dir_watchdog_threads = int(input_dir_watchdog_threads)
    event_handler.testssl_result_processor.threads = input_dir_watchdog_threads


    # schedule our config_dir file watchdog
    observer1 = Observer()
    observer1.schedule(result_handler_config_monitor, config_dir, recursive=True)
    observer1.start()
    logging.getLogger("watchdog.observers.inotify_buffer").setLevel("INFO")

    logging.info("Monitoring for new result handler config YAML files at: %s ",config_dir)

    # lets process any config files already there...
    config_dir_path_to_startup_scan = config_dir
    if config_dir_path_to_startup_scan.startswith("./") or not config_dir_path_to_startup_scan.startswith("/"):
        config_dir_path_to_startup_scan = os.getcwd() + "/" + config_dir_path_to_startup_scan.replace("./","")

    # load any pre existing configs
    for f in os.listdir(config_dir):
        result_handler_config_monitor.on_created(FileCreatedEvent(config_dir + "/" + os.path.basename(f)))

    # schedule our testssl.sh json result file watchdog
    observer2 = Observer()
    observer2.schedule(event_handler, input_dir, recursive=True)
    observer2.start()
    logging.getLogger("watchdog.observers.inotify_buffer").setLevel("INFO")

    logging.info("Monitoring for new testssl.sh result JSON files at: %s ",input_dir)


    # port...
    if (isinstance(httpserver_port,str)):
        httpserver_port = int(httpserver_port)

    # start local http server?
    httpdthread = None
    if httpserver_port is not None and isinstance(httpserver_port,int):
        logging.info("Starting HTTP server listening on: %d and serving up: %s" % (httpserver_port,httpserver_root_dir))
        resource = File(httpserver_root_dir)
        factory = Site(resource)
        endpoint = endpoints.TCP4ServerEndpoint(reactor, httpserver_port)
        endpoint.listen(factory)
        httpdthread = threading.Thread(target=reactor.run,args=(False,))
        httpdthread.daemon = True
        httpdthread.start()

    try:
        while True:
            time.sleep(30)
    except KeyboardInterrupt:
        observer1.stop()
        observer2.stop()
    observer1.join()
    observer2.join()




###########################
# Main program
##########################
if __name__ == '__main__':

0 Source : testssl_processor.py
with Apache License 2.0
from bitsofinfo

def init_watching(input_dir,
                 output_dir,
                 filename_filter,
                 watchdog_threads,
                 testssl_threads,
                 result_filename_prefix,
                 result_format,
                 testssl_path_if_missing,
                 output_dir_httpserver_port,
                 retain_output_days):


    # mthreaded...
    if (isinstance(watchdog_threads,str)):
        watchdog_threads = int(watchdog_threads)

    # port...
    if (isinstance(output_dir_httpserver_port,str)):
        output_dir_httpserver_port = int(output_dir_httpserver_port)

    # create watchdog to look for new files
    event_handler = TestsslInputFileMonitor()
    event_handler.filename_filter = filename_filter
    event_handler.set_threads(watchdog_threads)

    # Create a TestsslProcessor to consume the testssl_cmds files
    event_handler.testssl_processor = TestsslProcessor()
    event_handler.testssl_processor.retain_output_days = retain_output_days
    event_handler.testssl_processor.testssl_path_if_missing = testssl_path_if_missing
    event_handler.testssl_processor.output_dir = output_dir
    event_handler.testssl_processor.result_filename_prefix = result_filename_prefix
    event_handler.testssl_processor.result_format = result_format

    # give the processor the total number of threads to use
    # for processing testssl.sh cmds concurrently
    if (isinstance(testssl_threads,str)):
        testssl_threads = int(testssl_threads)
    event_handler.testssl_processor.threads = testssl_threads

    # schedule our file watchdog
    observer = Observer()
    observer.schedule(event_handler, input_dir, recursive=True)
    observer.start()
    logging.getLogger("watchdog.observers.inotify_buffer").setLevel("INFO")

    logging.info("Monitoring for new testssl_cmds files at: %s with filename filter: %s",input_dir,filename_filter)


    # start local http server?
    httpdthread = None
    if output_dir_httpserver_port is not None and isinstance(output_dir_httpserver_port,int):
        logging.info("Starting HTTP server listening on: %d and serving up: %s" % (output_dir_httpserver_port,output_dir))
        resource = File(output_dir)
        factory = Site(resource)
        endpoint = endpoints.TCP4ServerEndpoint(reactor, output_dir_httpserver_port)
        endpoint.listen(factory)
        httpdthread = threading.Thread(target=reactor.run,args=(False,))
        httpdthread.daemon = True
        httpdthread.start()

    try:
        while True:
            time.sleep(30)
    except KeyboardInterrupt:
        observer.stop()
    observer.join()


###########################
# Main program
##########################
if __name__ == '__main__':

0 Source : endpoint.py
with MIT License
from fbla-competitive-events

def create_listening_endpoint_from_config(config, cbdir, reactor, log):
    """
    Create a Twisted stream server endpoint from a Crossbar.io transport configuration.

    See: https://twistedmatrix.com/documents/current/api/twisted.internet.interfaces.IStreamServerEndpoint.html

    :param config: The transport configuration.
    :type config: dict
    :param cbdir: Crossbar.io node directory (we need this for TLS key/certificates).
    :type cbdir: str
    :param reactor: The reactor to use for endpoint creation.
    :type reactor: obj

    :returns obj -- An instance implementing IStreamServerEndpoint
    """
    endpoint = None

    # a TCP endpoint
    #
    if config['type'] == 'tcp':

        # the TCP protocol version (v4 or v6)
        #
        version = int(config.get('version', 4))

        # the listening port
        if type(config['port']) is six.text_type:
            # read port from environment variable ..
            try:
                port = int(environ[config['port'][1:]])
            except Exception as e:
                log.warn("Could not read listening port from env var: {}".format(e))
                raise
        else:
            port = config['port']

        # the listening interface
        #
        interface = str(config.get('interface', '').strip())

        # the TCP accept queue depth
        #
        backlog = int(config.get('backlog', 50))

        if 'tls' in config:
            # create a TLS server endpoint
            #
            if _HAS_TLS:
                # TLS server context
                context = _create_tls_server_context(config['tls'], cbdir, log)

                if version == 4:
                    endpoint = SSL4ServerEndpoint(reactor,
                                                  port,
                                                  context,
                                                  backlog=backlog,
                                                  interface=interface)
                elif version == 6:
                    raise Exception("TLS on IPv6 not implemented")
                else:
                    raise Exception("invalid TCP protocol version {}".format(version))
            else:
                raise Exception("TLS transport requested, but TLS packages not available:\n{}".format(_LACKS_TLS_MSG))

        else:
            # create a non-TLS server endpoint
            #
            if version == 4:
                endpoint = TCP4ServerEndpoint(reactor,
                                              port,
                                              backlog=backlog,
                                              interface=interface)
            elif version == 6:
                endpoint = TCP6ServerEndpoint(reactor,
                                              port,
                                              backlog=backlog,
                                              interface=interface)
            else:
                raise Exception("invalid TCP protocol version {}".format(version))

    # a Unix Domain Socket endpoint
    #
    elif config['type'] == 'unix':

        # the accept queue depth
        #
        backlog = int(config.get('backlog', 50))

        # the path
        #
        path = FilePath(join(cbdir, config['path']))

        # if there is already something there, delete it.
        #
        if path.exists():
            log.info(("{path} exists, attempting to remove before using as a "
                     "UNIX socket"), path=path)
            path.remove()

        # create the endpoint
        #
        endpoint = UNIXServerEndpoint(reactor, path.path, backlog=backlog)

    else:
        raise Exception("invalid endpoint type '{}'".format(config['type']))

    return endpoint


def create_listening_port_from_config(config, cbdir, factory, reactor, log):

0 Source : tap.py
with MIT License
from fbla-competitive-events

    def _getEndpoints(self, reactor, service):
        """
        Return a list of endpoints for the specified service, constructing
        defaults if necessary.

        If no endpoints were configured for the service and the protocol
        was not explicitly disabled with a I{--no-*} option, a default
        endpoint for the service is created.

        @type reactor: L{IReactorTCP   <  twisted.internet.interfaces.IReactorTCP>}
            provider
        @param reactor: If any endpoints are created, the reactor with
            which they are created.

        @type service: L{bytes}
        @param service: The type of service for which to retrieve endpoints,
            either C{b'pop3'} or C{b'smtp'}.

        @rtype: L{list} of L{IStreamServerEndpoint
             < twisted.internet.interfaces.IStreamServerEndpoint>} provider
        @return: The endpoints for the specified service as configured by the
            command line parameters.
        """
        if service == 'pop3' and self['pop3s'] and len(self[service]) == 1:
            # The single endpoint here is the POP3S service we added in
            # postOptions.  Include the default endpoint alongside it.
            return self[service] + [
                endpoints.TCP4ServerEndpoint(
                    reactor, self._protoDefaults[service])]
        elif self[service]:
            # For any non-POP3S case, if there are any services set up, just
            # return those.
            return self[service]
        elif self['no-' + service]:
            # If there are no services, but the service was explicitly disabled,
            # return nothing.
            return []
        else:
            # Otherwise, return the old default service.
            return [
                endpoints.TCP4ServerEndpoint(
                    reactor, self._protoDefaults[service])]


    def postOptions(self):

0 Source : test_options.py
with MIT License
from fbla-competitive-events

    def test_barePort(self):
        """
        A bare port passed to I{--pop3} results in deprecation warning in
        addition to a TCP4ServerEndpoint.
        """
        options = Options()
        options.parseOptions(['--pop3', '8110'])
        self.assertEqual(len(options['pop3']), 1)
        self.assertIsInstance(
            options['pop3'][0], endpoints.TCP4ServerEndpoint)
        warnings = self.flushWarnings([options.opt_pop3])
        self.assertEqual(len(warnings), 1)
        self.assertEqual(warnings[0]['category'], DeprecationWarning)
        self.assertEqual(
            warnings[0]['message'],
            "Specifying plain ports and/or a certificate is deprecated since "
            "Twisted 11.0; use endpoint descriptions instead.")


    def _endpointTest(self, service):

0 Source : p2p.py
with GNU General Public License v3.0
from kudelskisecurity

    def start(self):
        """Start this p2p node:
          * Listen to incoming connections
          * Connect to initial peers
          * Start the REST API
          * Start the explorer (optional)
        """
        # start the server
        s = TCP4ServerEndpoint(reactor, self.port)
        s.listen(self.factory)
        logger.info("[p2p] server listening")
        logger.info(f"Magic: {self.magic}")

        # connect to peers
        for address in self.addresses:
            self._connect(address)

        # setup the API
        logger.info("[api] Starting clientAPI on port {}...".format(self.api_port))
        api_resource = WSGIResource(reactor, reactor.getThreadPool(), self.api_app)
        api_site = Site(api_resource)
        reactor.listenTCP(self.api_port, api_site)

        # setup the explorer
        if self.explorer_enabled:
            logger.info("[api] Starting explorer on port {}...".format(self.explorer_port))
            explorer_resource = WSGIResource(reactor, reactor.getThreadPool(), self.explorer_app)
            explorer_site = Site(explorer_resource)
            reactor.listenTCP(self.explorer_port, explorer_site)

        # start the reactor
        logger.info("[p2p] reactor started")
        self.bc_saver.start(BLOCKCHAIN_SAVE_INTERVAL_SECONDS, now=False)
        reactor.run()

    def stop(self):

0 Source : raspiled_listener.py
with MIT License
from michaeljtbrooks

def start_if_not_running():
    """
    Checks if the process is running, if not, starts it!
    """
    pids = get_matching_pids(APP_NAME, exclude_self=True)  # Will remove own PID
    pids = filter(bool, pids)
    if not pids:  # No match! Implies we need to fire up the listener
        logging.info("[STARTING] Raspiled Listener with PID %s" % str(os.getpid()))
        # First the web
        factory = RaspiledControlSite(timeout=8)  # 8s timeout
        try:
            pi_port = int(RESOLVED_USER_SETTINGS.get('pi_port', 9090))
        except (TypeError, ValueError):
            raise ConfigurationError("You have an invalid value for 'pi_port' in your settings. This needs to be a valid port number (integer).")
        endpoint = endpoints.TCP4ServerEndpoint(reactor, pi_port)
        endpoint.listen(factory)
        # factory.setup_broadcasting(reactor)  # Uncomment to broadcast stuff over network!
        reactor.run()
    else:
        logging.info("Raspiled Listener already running with PID %s" % ", ".join(pids))


if __name__ == "__main__":

0 Source : base.py
with MIT License
from opacam

    def __init__(self, port, coherence, unittests=False):
        log.LogAble.__init__(self)
        self.coherence = coherence
        from coherence.web.ui import Web, IWeb, WebUI
        from twisted.web import server, resource
        from twisted.python.components import registerAdapter

        def resource_factory(original):
            return WebUI(IWeb, original)

        registerAdapter(resource_factory, Web, resource.IResource)

        self.web_root_resource = WebUI(coherence)
        if not unittests:
            site_cls = server.Site
        else:
            from tests.web_utils import DummySite

            site_cls = DummySite
        self.site = site_cls(self.web_root_resource)

        self.endpoint = endpoints.TCP4ServerEndpoint(reactor, port)
        self._endpoint_listen(coherence, port)

        self.ws_endpoint = endpoints.TCP4ServerEndpoint(reactor, 9000)
        self._ws_endpoint_listen(coherence)

    def _endpoint_listen(self, coherence, port):

0 Source : vmware_exporter.py
with BSD 3-Clause "New" or "Revised" License
from pryorda

def main(argv=None):
    """ start up twisted reactor """
    parser = argparse.ArgumentParser(description='VMWare metrics exporter for Prometheus')
    parser.add_argument('-c', '--config', dest='config_file',
                        default=None, help="configuration file")
    parser.add_argument('-a', '--address', dest='address', type=str,
                        default='', help="HTTP address to expose metrics")
    parser.add_argument('-p', '--port', dest='port', type=int,
                        default=9272, help="HTTP port to expose metrics")
    parser.add_argument('-l', '--loglevel', dest='loglevel',
                        default="INFO", help="Set application loglevel INFO, DEBUG")
    parser.add_argument('-v', '--version', action="version",
                        version='vmware_exporter {version}'.format(version=__version__),
                        help='Print version and exit')

    args = parser.parse_args(argv or sys.argv[1:])

    numeric_level = getattr(logging, args.loglevel.upper(), None)
    if not isinstance(numeric_level, int):
        raise ValueError("Invalid log level: {level}".format(level=args.loglevel))
    logging.basicConfig(level=numeric_level, format='%(asctime)s %(levelname)s:%(message)s')

    reactor.suggestThreadPoolSize(25)

    factory = Site(registerEndpoints(args))
    logging.info("Starting web server on port {address}:{port}".format(address=args.address, port=args.port))
    endpoint = endpoints.TCP4ServerEndpoint(reactor, args.port, interface=args.address)
    endpoint.listen(factory)
    reactor.run()


if __name__ == '__main__':