twisted.internet.endpoints.clientFromString

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

33 Examples 7

3 Source : test_endpoints.py
with MIT License
from autofelix

    def test_tcp(self):
        """
        When passed a TCP strports description, L{endpoints.clientFromString}
        returns a L{TCP4ClientEndpoint} instance initialized with the values
        from the string.
        """
        reactor = object()
        client = endpoints.clientFromString(
            reactor,
            "tcp:host=example.com:port=1234:timeout=7:bindAddress=10.0.0.2")
        self.assertIsInstance(client, endpoints.TCP4ClientEndpoint)
        self.assertIs(client._reactor, reactor)
        self.assertEqual(client._host, "example.com")
        self.assertEqual(client._port, 1234)
        self.assertEqual(client._timeout, 7)
        self.assertEqual(client._bindAddress, ("10.0.0.2", 0))


    def test_tcpPositionalArgs(self):

3 Source : test_endpoints.py
with MIT License
from autofelix

    def test_tcpPositionalArgs(self):
        """
        When passed a TCP strports description using positional arguments,
        L{endpoints.clientFromString} returns a L{TCP4ClientEndpoint} instance
        initialized with the values from the string.
        """
        reactor = object()
        client = endpoints.clientFromString(
            reactor,
            "tcp:example.com:1234:timeout=7:bindAddress=10.0.0.2")
        self.assertIsInstance(client, endpoints.TCP4ClientEndpoint)
        self.assertIs(client._reactor, reactor)
        self.assertEqual(client._host, "example.com")
        self.assertEqual(client._port, 1234)
        self.assertEqual(client._timeout, 7)
        self.assertEqual(client._bindAddress, ("10.0.0.2", 0))


    def test_tcpHostPositionalArg(self):

3 Source : test_endpoints.py
with MIT License
from autofelix

    def test_tcpHostPositionalArg(self):
        """
        When passed a TCP strports description specifying host as a positional
        argument, L{endpoints.clientFromString} returns a L{TCP4ClientEndpoint}
        instance initialized with the values from the string.
        """
        reactor = object()

        client = endpoints.clientFromString(
            reactor,
            "tcp:example.com:port=1234:timeout=7:bindAddress=10.0.0.2")
        self.assertEqual(client._host, "example.com")
        self.assertEqual(client._port, 1234)


    def test_tcpPortPositionalArg(self):

3 Source : test_endpoints.py
with MIT License
from autofelix

    def test_tcpPortPositionalArg(self):
        """
        When passed a TCP strports description specifying port as a positional
        argument, L{endpoints.clientFromString} returns a L{TCP4ClientEndpoint}
        instance initialized with the values from the string.
        """
        reactor = object()
        client = endpoints.clientFromString(
            reactor,
            "tcp:host=example.com:1234:timeout=7:bindAddress=10.0.0.2")
        self.assertEqual(client._host, "example.com")
        self.assertEqual(client._port, 1234)


    def test_tcpDefaults(self):

3 Source : test_endpoints.py
with MIT License
from autofelix

    def test_tcpDefaults(self):
        """
        A TCP strports description may omit I{timeout} or I{bindAddress} to
        allow the default to be used.
        """
        reactor = object()
        client = endpoints.clientFromString(
            reactor,
            "tcp:host=example.com:port=1234")
        self.assertEqual(client._timeout, 30)
        self.assertIsNone(client._bindAddress)


    def test_unix(self):

3 Source : test_endpoints.py
with MIT License
from autofelix

    def test_unix(self):
        """
        When passed a UNIX strports description, L{endpoints.clientFromString}
        returns a L{UNIXClientEndpoint} instance initialized with the values
        from the string.
        """
        reactor = object()
        client = endpoints.clientFromString(
            reactor,
            "unix:path=/var/foo/bar:lockfile=1:timeout=9")
        self.assertIsInstance(client, endpoints.UNIXClientEndpoint)
        self.assertIs(client._reactor, reactor)
        self.assertEqual(client._path, "/var/foo/bar")
        self.assertEqual(client._timeout, 9)
        self.assertTrue(client._checkPID)


    def test_unixDefaults(self):

3 Source : test_endpoints.py
with MIT License
from autofelix

    def test_unixDefaults(self):
        """
        A UNIX strports description may omit I{lockfile} or I{timeout} to allow
        the defaults to be used.
        """
        client = endpoints.clientFromString(
            object(), "unix:path=/var/foo/bar")
        self.assertEqual(client._timeout, 30)
        self.assertFalse(client._checkPID)


    def test_unixPathPositionalArg(self):

3 Source : test_endpoints.py
with MIT License
from autofelix

    def test_unixPathPositionalArg(self):
        """
        When passed a UNIX strports description specifying path as a positional
        argument, L{endpoints.clientFromString} returns a L{UNIXClientEndpoint}
        instance initialized with the values from the string.
        """
        reactor = object()
        client = endpoints.clientFromString(
            reactor,
            "unix:/var/foo/bar:lockfile=1:timeout=9")
        self.assertIsInstance(client, endpoints.UNIXClientEndpoint)
        self.assertIs(client._reactor, reactor)
        self.assertEqual(client._path, "/var/foo/bar")
        self.assertEqual(client._timeout, 9)
        self.assertTrue(client._checkPID)


    def test_typeFromPlugin(self):

3 Source : test_endpoints.py
with MIT License
from autofelix

    def test_typeFromPlugin(self):
        """
        L{endpoints.clientFromString} looks up plugins of type
        L{IStreamClientEndpoint} and constructs endpoints from them.
        """
        addFakePlugin(self)
        notAReactor = object()
        clientEndpoint = endpoints.clientFromString(
            notAReactor, "crfake:alpha:beta:cee=dee:num=1")
        from twisted.plugins.fakeendpoint import fakeClientWithReactor
        self.assertIs(clientEndpoint.parser, fakeClientWithReactor)
        self.assertEqual(clientEndpoint.args, (notAReactor, 'alpha', 'beta'))
        self.assertEqual(clientEndpoint.kwargs, dict(cee='dee', num='1'))


    def test_unknownType(self):

3 Source : test_endpoints.py
with MIT License
from autofelix

    def test_unknownType(self):
        """
        L{endpoints.clientFromString} raises C{ValueError} when given an
        unknown endpoint type.
        """
        value = self.assertRaises(
            # faster-than-light communication not supported
            ValueError, endpoints.clientFromString, None,
            "ftl:andromeda/carcosa/hali/2387")
        self.assertEqual(
            str(value),
            "Unknown endpoint type: 'ftl'")


    def test_stringParserWithReactor(self):

3 Source : test_endpoints.py
with MIT License
from autofelix

    def test_sslWithDefaults(self):
        """
        When passed an SSL strports description without extra arguments,
        L{clientFromString} returns a L{SSL4ClientEndpoint} instance
        whose context factory is initialized with default values.
        """
        reactor = object()
        client = endpoints.clientFromString(reactor, "ssl:example.net:4321")
        self.assertIsInstance(client, endpoints.SSL4ClientEndpoint)
        self.assertIs(client._reactor, reactor)
        self.assertEqual(client._host, "example.net")
        self.assertEqual(client._port, 4321)
        certOptions = client._sslContextFactory
        self.assertEqual(certOptions.method, SSLv23_METHOD)
        self.assertIsNone(certOptions.certificate)
        self.assertIsNone(certOptions.privateKey)


    def test_unreadableCertificate(self):

3 Source : test_endpoints.py
with MIT License
from autofelix

    def test_sslSimple(self):
        """
        When passed an SSL strports description without any extra parameters,
        L{clientFromString} returns a simple non-verifying endpoint that will
        speak SSL.
        """
        reactor = object()
        client = endpoints.clientFromString(
            reactor, "ssl:host=simple.example.org:port=4321")
        certOptions = client._sslContextFactory
        self.assertIsInstance(certOptions, CertificateOptions)
        self.assertFalse(certOptions.verify)
        ctx = certOptions.getContext()
        self.assertIsInstance(ctx, ContextType)



class AdoptedStreamServerEndpointTests(ServerEndpointTestCaseMixin,

3 Source : test_endpoints.py
with MIT License
from autofelix

    def test_tlsWithDefaults(self):
        """
        When passed a C{tls:} strports description without extra arguments,
        L{clientFromString} returns a client endpoint whose context factory is
        initialized with default values.
        """
        reactor = object()
        endpoint = endpoints.clientFromString(reactor, b'tls:example.com:443')
        creator = connectionCreatorFromEndpoint(reactor, endpoint)
        self.assertEqual(creator._hostname, u'example.com')
        self.assertEqual(endpoint._wrappedEndpoint._hostBytes, b'example.com')



def replacingGlobals(function, **newGlobals):

3 Source : NodeLeader.py
with MIT License
from ddi-lab

    def SetupConnection(self, host, port):
        logger.debug("Setting up connection! %s %s " % (host, port))

        factory = Factory.forProtocol(NeoNode)
        endpoint = clientFromString(reactor, "tcp:host=%s:port=%s:timeout=5" % (host, port))

        connectingService = ClientService(
            endpoint,
            factory,
            retryPolicy=backoffPolicy(.5, factor=3.0)
        )
        connectingService.startService()

    def Shutdown(self):

3 Source : snippet.py
with Apache License 2.0
from dockerizeme

def main(reactor, description):
    endpoint = endpoints.clientFromString(reactor, description)
    factory = MyFirstIRCFactory()
    d = endpoint.connect(factory)
    d.addCallback(lambda protocol: protocol.deferred)
    return d


if __name__ == '__main__':

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

    def connectionMade(self):
        self.log.debug("EndpointForwardingProtocol.connectionMade")
        self._destFactory = DestEndpointForwardingFactory(self)
        self._destEndpoint = clientFromString(self.factory.service._reactor,
                                              self.factory.service._destEndpointDescriptor)
        self._destEndpointPort = yield self._destEndpoint.connect(self._destFactory)

    def dataReceived(self, data):

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

    def test_utf8Encoding(self):
        """
        The hostname passed to L{clientFromString} is treated as utf-8 bytes;
        it is then encoded as IDNA when it is passed along to
        L{HostnameEndpoint}, and passed as unicode to L{optionsForClientTLS}.
        """
        reactor = object()
        endpoint = endpoints.clientFromString(
            reactor, b'tls:\xc3\xa9xample.example.com:443'
        )
        self.assertEqual(
            endpoint._wrappedEndpoint._host, b'xn--xample-9ua.example.com')
        connectionCreator = connectionCreatorFromEndpoint(reactor, endpoint)
        self.assertEqual(connectionCreator._hostname,
                         u'\xe9xample.example.com')


    def test_tls(self):

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

    def test_tlsWithDefaults(self):
        """
        When passed a C{tls:} strports description without extra arguments,
        L{clientFromString} returns a client endpoint whose context factory is
        initialized with default values.
        """
        reactor = object()
        endpoint = endpoints.clientFromString(reactor, b'tls:example.com:443')
        creator = connectionCreatorFromEndpoint(reactor, endpoint)
        self.assertEqual(creator._hostname, u'example.com')
        self.assertEqual(endpoint._wrappedEndpoint._host, b'example.com')



def replacingGlobals(function, **newGlobals):

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

    def parseStreamClient(self, *args, **options):
        if _HAS_REACTOR_ARG:
            reactor = args[0]
            if len(args) != 2:
                raise RuntimeError("autobahn: client plugin takes exactly one positional argument")
            description = args[1]
        else:
            from twisted.internet import reactor
            if len(args) != 1:
                raise RuntimeError("autobahn: client plugin takes exactly one positional argument")
            description = args[0]
        opts = _parseOptions(options)
        endpoint = clientFromString(reactor, description)
        return AutobahnClientEndpoint(reactor, endpoint, opts)


@implementer(IPlugin)

3 Source : test_status.py
with Apache License 2.0
from HathorNetwork

    def test_connecting_peers(self):
        address = '192.168.1.1:54321'
        endpoint = endpoints.clientFromString(self.manager.reactor, 'tcp:{}'.format(address))
        deferred = endpoint.connect
        self.manager.connections.connecting_peers[endpoint] = deferred

        response = yield self.web.get("status")
        data = response.json_value()
        connecting = data['connections']['connecting_peers']
        self.assertEqual(len(connecting), 1)
        self.assertEqual(connecting[0]['address'], address)
        self.assertIsNotNone(connecting[0]['deferred'])


class SyncV1StatusTest(unittest.SyncV1Params, BaseStatusTest):

3 Source : client.py
with GNU General Public License v3.0
from marcus-santos

    def __init__(self, live=False, retryPolicy=None,
                 clock=None, prepareConnection=None):
        host = "ssl:" + (self.PROXY_LIVE if live else self.PROXY_DEMO)
        endpoint = clientFromString(reactor, host)
        factory = Client.Factory.forProtocol(Client.Protocol, client=self)
        super().__init__(endpoint, factory, retryPolicy=retryPolicy,
                         clock=clock, prepareConnection=prepareConnection)

    def start(self, timeout=None):

3 Source : net_twisted.py
with Apache License 2.0
from rethinkdb

    def _connectTimeout(self, factory, timeout):
        try:
            # TODO: use ssl options
            # TODO: this doesn't work for literal IPv6 addresses like '::1'
            args = "tcp:%s:%d" % (self._parent.host, self._parent.port)

            if timeout is not None:
                args = args + (":timeout=%d" % timeout)

            endpoint = clientFromString(reactor, args)
            p = yield endpoint.connect(factory)
            returnValue(p)
        except TimeoutError:
            raise ReqlTimeoutError()

    @inlineCallbacks

3 Source : client.py
with MIT License
from spotware

    def __init__(self, host, port, protocol, retryPolicy=None, clock=None, prepareConnection=None, numberOfMessagesToSendPerSecond=5):
        self._runningReactor = reactor
        self.numberOfMessagesToSendPerSecond = numberOfMessagesToSendPerSecond
        endpoint = clientFromString(self._runningReactor, f"ssl:{host}:{port}")
        factory = Factory.forProtocol(protocol, client=self)
        super().__init__(endpoint, factory, retryPolicy=retryPolicy, clock=clock, prepareConnection=prepareConnection)
        self._events = dict()
        self._responseDeferreds = dict()
        self.isConnected = False

    def startService(self):

0 Source : test_endpoints.py
with MIT License
from autofelix

    def test_stringParserWithReactor(self):
        """
        L{endpoints.clientFromString} will pass a reactor to plugins
        implementing the L{IStreamClientEndpointStringParserWithReactor}
        interface.
        """
        addFakePlugin(self)
        reactor = object()
        clientEndpoint = endpoints.clientFromString(
            reactor, 'crfake:alpha:beta:cee=dee:num=1')
        from twisted.plugins.fakeendpoint import fakeClientWithReactor
        self.assertEqual(
            (clientEndpoint.parser,
             clientEndpoint.args,
             clientEndpoint.kwargs),
            (fakeClientWithReactor,
             (reactor, 'alpha', 'beta'),
             dict(cee='dee', num='1')))



class SSLClientStringTests(unittest.TestCase):

0 Source : test_endpoints.py
with MIT License
from autofelix

    def test_ssl(self):
        """
        When passed an SSL strports description, L{clientFromString} returns a
        L{SSL4ClientEndpoint} instance initialized with the values from the
        string.
        """
        reactor = object()
        client = endpoints.clientFromString(
            reactor,
            "ssl:host=example.net:port=4321:privateKey=%s:"
            "certKey=%s:bindAddress=10.0.0.3:timeout=3:caCertsDir=%s" %
            (escapedPEMPathName, escapedPEMPathName, escapedCAsPathName))
        self.assertIsInstance(client, endpoints.SSL4ClientEndpoint)
        self.assertIs(client._reactor, reactor)
        self.assertEqual(client._host, "example.net")
        self.assertEqual(client._port, 4321)
        self.assertEqual(client._timeout, 3)
        self.assertEqual(client._bindAddress, ("10.0.0.3", 0))
        certOptions = client._sslContextFactory
        self.assertIsInstance(certOptions, CertificateOptions)
        self.assertEqual(certOptions.method, SSLv23_METHOD)
        self.assertTrue(certOptions._options & OP_NO_SSLv3)
        ctx = certOptions.getContext()
        self.assertIsInstance(ctx, ContextType)
        self.assertEqual(Certificate(certOptions.certificate), testCertificate)
        privateCert = PrivateCertificate(certOptions.certificate)
        privateCert._setPrivateKey(KeyPair(certOptions.privateKey))
        self.assertEqual(privateCert, testPrivateCertificate)
        expectedCerts = [
            Certificate.loadPEM(x.getContent()) for x in
            [casPath.child("thing1.pem"), casPath.child("thing2.pem")]
            if x.basename().lower().endswith('.pem')
        ]
        addedCerts = []
        class ListCtx(object):
            def get_cert_store(self):
                class Store(object):
                    def add_cert(self, cert):
                        addedCerts.append(cert)
                return Store()
        certOptions.trustRoot._addCACertsToContext(ListCtx())
        self.assertEqual(
            sorted((Certificate(x) for x in addedCerts),
                   key=lambda cert: cert.digest()),
            sorted(expectedCerts,
                   key=lambda cert: cert.digest())
        )


    def test_sslPositionalArgs(self):

0 Source : test_endpoints.py
with MIT License
from autofelix

    def test_sslPositionalArgs(self):
        """
        When passed an SSL strports description, L{clientFromString} returns a
        L{SSL4ClientEndpoint} instance initialized with the values from the
        string.
        """
        reactor = object()
        client = endpoints.clientFromString(
            reactor,
            "ssl:example.net:4321:privateKey=%s:"
            "certKey=%s:bindAddress=10.0.0.3:timeout=3:caCertsDir=%s" %
            (escapedPEMPathName, escapedPEMPathName, escapedCAsPathName))
        self.assertIsInstance(client, endpoints.SSL4ClientEndpoint)
        self.assertIs(client._reactor, reactor)
        self.assertEqual(client._host, "example.net")
        self.assertEqual(client._port, 4321)
        self.assertEqual(client._timeout, 3)
        self.assertEqual(client._bindAddress, ("10.0.0.3", 0))


    def test_sslWithDefaults(self):

0 Source : test_endpoints.py
with MIT License
from autofelix

    def test_hostnameEndpointConstruction(self):
        """
        A L{HostnameEndpoint} is constructed from parameters passed to
        L{clientFromString}.
        """
        reactor = object()
        endpoint = endpoints.clientFromString(
            reactor,
            nativeString(
                'tls:example.com:443:timeout=10:bindAddress=127.0.0.1'))
        hostnameEndpoint = endpoint._wrappedEndpoint
        self.assertIs(hostnameEndpoint._reactor, reactor)
        self.assertEqual(hostnameEndpoint._hostBytes, b'example.com')
        self.assertEqual(hostnameEndpoint._port, 443)
        self.assertEqual(hostnameEndpoint._timeout, 10)
        self.assertEqual(hostnameEndpoint._bindAddress,
                         nativeString('127.0.0.1'))


    def test_utf8Encoding(self):

0 Source : test_endpoints.py
with MIT License
from autofelix

    def test_utf8Encoding(self):
        """
        The hostname passed to L{clientFromString} is treated as utf-8 bytes;
        it is then encoded as IDNA when it is passed along to
        L{HostnameEndpoint}, and passed as unicode to L{optionsForClientTLS}.
        """
        reactor = object()
        endpoint = endpoints.clientFromString(
            reactor, b'tls:\xc3\xa9xample.example.com:443'
        )
        self.assertEqual(
            endpoint._wrappedEndpoint._hostBytes,
            b'xn--xample-9ua.example.com'
        )
        connectionCreator = connectionCreatorFromEndpoint(
            reactor, endpoint)
        self.assertEqual(connectionCreator._hostname,
                         u'\xe9xample.example.com')


    def test_tls(self):

0 Source : snippet.py
with Apache License 2.0
from dockerizeme

    def get_endpoint(self, domain):
        resolved_name = self.resolve(domain)

        if resolved_name:
            logger.info('Resolved domain %s to %s.onion',
                        domain, resolved_name)
            endpoint_string = 'tor:host={}.onion:port=443'.format(
                self.resolve(domain))

            try:
                endpoint = clientFromString(reactor, endpoint_string)
            except ValueError:
                logger.exception('Error creating client endpoint. Maybe a '
                                 'suitable endpoint parser is not available.')
                return None

            return endpoint
        else:
            logger.warn('Could not resolve domain %s.', domain)
            return None


class SSLContext(object):

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

    def test_hostnameEndpointConstruction(self):
        """
        A L{HostnameEndpoint} is constructed from parameters passed to
        L{clientFromString}.
        """
        reactor = object()
        endpoint = endpoints.clientFromString(
            reactor,
            nativeString(
                'tls:example.com:443:timeout=10:bindAddress=127.0.0.1'))
        hostnameEndpoint = endpoint._wrappedEndpoint
        self.assertIs(hostnameEndpoint._reactor, reactor)
        self.assertEqual(hostnameEndpoint._host, b'example.com')
        self.assertEqual(hostnameEndpoint._port, 443)
        self.assertEqual(hostnameEndpoint._timeout, 10)
        self.assertEqual(hostnameEndpoint._bindAddress,
                         nativeString('127.0.0.1'))


    def test_utf8Encoding(self):

0 Source : test_worker_comm.py
with GNU General Public License v2.0
from flathub

    def connectWorker(self, waitForBuilderList=True):
        """
        Connect a worker the master via PB

        @param waitForBuilderList: don't return until the setBuilderList has
        been called
        @returns: L{FakeWorkerWorker} and a Deferred that will fire when it
        is detached; via deferred
        """
        factory = pb.PBClientFactory()
        creds = credentials.UsernamePassword(b"testworker", b"pw")
        setBuilderList_d = defer.Deferred()
        workerworker = FakeWorkerWorker(
            lambda: setBuilderList_d.callback(None))

        login_d = factory.login(creds, workerworker)

        @login_d.addCallback
        def logged_in(persp):
            workerworker.setMasterPerspective(persp)

            # set up to hear when the worker side disconnects
            workerworker.detach_d = defer.Deferred()
            persp.broker.notifyOnDisconnect(
                lambda: workerworker.detach_d.callback(None))
            self._detach_deferreds.append(workerworker.detach_d)

            return workerworker

        self.endpoint = clientFromString(
                reactor, self.client_connection_string_tpl.format(port=self.port))
        connected_d = self.endpoint.connect(factory)

        dlist = [connected_d, login_d]
        if waitForBuilderList:
            dlist.append(setBuilderList_d)

        d = defer.DeferredList(dlist,
                               consumeErrors=True, fireOnOneErrback=True)
        d.addCallback(lambda _: workerworker)
        return d

    def workerSideDisconnect(self, worker):

0 Source : pb.py
with GNU General Public License v2.0
from flathub

    def __init__(self, buildmaster_host, port, name, passwd, basedir,
                 keepalive, usePTY=None, keepaliveTimeout=None, umask=None,
                 maxdelay=None, numcpus=None, unicode_encoding=None, useTls=None,
                 allow_shutdown=None, maxRetries=None, connection_string=None,
                 delete_leftover_dirs=False):

        assert usePTY is None, "worker-side usePTY is not supported anymore"
        assert (connection_string is None or
                (buildmaster_host, port) == (None, None)), (
                    "If you want to supply a connection string, "
                    "then set host and port to None")

        service.MultiService.__init__(self)
        WorkerBase.__init__(
            self, name, basedir, umask=umask, unicode_encoding=unicode_encoding,
            delete_leftover_dirs=delete_leftover_dirs)
        if keepalive == 0:
            keepalive = None

        name = unicode2bytes(name, self.bot.unicode_encoding)
        passwd = unicode2bytes(passwd, self.bot.unicode_encoding)

        self.numcpus = numcpus
        self.shutdown_loop = None

        if allow_shutdown == 'signal':
            if not hasattr(signal, 'SIGHUP'):
                raise ValueError("Can't install signal handler")
        elif allow_shutdown == 'file':
            self.shutdown_file = os.path.join(basedir, 'shutdown.stamp')
            self.shutdown_mtime = 0

        self.allow_shutdown = allow_shutdown
        bf = self.bf = BotFactory(buildmaster_host, port, keepalive, maxdelay)
        bf.startLogin(
            credentials.UsernamePassword(name, passwd), client=self.bot)
        if connection_string is None:
            if useTls:
                connection_type = 'tls'
            else:
                connection_type = 'tcp'

            connection_string = '{}:host={}:port={}'.format(
                connection_type,
                buildmaster_host.replace(':', r'\:'),  # escape ipv6 addresses
                port)
        endpoint = clientFromString(reactor, connection_string)

        def policy(attempt):
            if maxRetries and attempt >= maxRetries:
                reactor.stop()
            return backoffPolicy()(attempt)
        pb_service = ClientService(endpoint, bf,
                                   retryPolicy=policy)
        self.addService(pb_service)

    def startService(self):

0 Source : manager.py
with Apache License 2.0
from HathorNetwork

    def connect_to(self, description: str, peer: Optional[PeerId] = None, use_ssl: Optional[bool] = None) -> None:
        """ Attempt to connect to a peer, even if a connection already exists.
        Usually you should call `connect_to_if_not_connected`.

        If `use_ssl` is True, then the connection will be wraped by a TLS.
        """
        if use_ssl is None:
            use_ssl = self.ssl
        connection_string, peer_id = description_to_connection_string(description)
        # When using twisted endpoints we can't have // in the connection string
        endpoint_url = connection_string.replace('//', '')
        endpoint = endpoints.clientFromString(self.reactor, endpoint_url)

        if self.localhost_only:
            if ('127.0.0.1' not in endpoint_url) and ('localhost' not in endpoint_url):
                return

        if use_ssl:
            certificate_options = self.my_peer.get_certificate_options()
            factory = TLSMemoryBIOFactory(certificate_options, True, self.client_factory)
        else:
            factory = self.client_factory

        deferred = endpoint.connect(factory)
        self.connecting_peers[endpoint] = _ConnectingPeer(connection_string, deferred)

        deferred.addCallback(self._connect_to_callback, peer, endpoint, connection_string, peer_id)
        deferred.addErrback(self.on_connection_failure, peer, endpoint)
        self.log.info('connect to ', endpoint=description)

    def listen(self, description: str, use_ssl: Optional[bool] = None) -> IStreamServerEndpoint: