Python twisted.internet.endpoints.TCP4ClientEndpoint() Examples

The following are 30 code examples of twisted.internet.endpoints.TCP4ClientEndpoint(). 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 twisted.internet.endpoints , or try the search function .
Example #1
Source File: test_endpoints.py    From learn_python3_spider with MIT License 6 votes vote down vote up
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)) 
Example #2
Source File: test_streamedlogs.py    From gridsync with GNU General Public License v3.0 6 votes vote down vote up
def test_binary_messages_dropped(reactor, tahoe):
    from twisted.internet import reactor as real_reactor

    server = BinaryMessageServerProtocol()

    client = yield connect_to_log_endpoint(
        reactor, tahoe, real_reactor, lambda: server,
    )
    # client is a _WrappingProtocol because the implementation uses
    # TCP4ClientEndpoint which puts a _WrappingFactory into the reactor.  Then
    # connect_to_log_endpoint takes the _WrappingFactory out of the _mock_
    # reactor it supplied and puts it into a new TCP4ClientEndpoint and uses
    # that against a real reactor.  The connection gets set up and the
    # _WrappingFactory creates a _WrappingProtocol which the new
    # TCP4ClientEndpoint happily hands back to us.
    #
    # Sadly, this hack makes us dependent on the implementation of endpoints,
    # the use of endpoints in streamedlogs.py, and the use of endpoints in
    # connect_to_log_endpoint.
    #
    # Maybe it would be good to try to use twisted.test.iosim instead?  Or
    # build something like RequestTraversalAgent but for Autobahn/WebSocket.
    yield client._wrappedProtocol.is_closed

    assert tahoe.streamedlogs.get_streamed_log_messages() == [] 
Example #3
Source File: test_streamedlogs.py    From gridsync with GNU General Public License v3.0 6 votes vote down vote up
def connect_to_log_endpoint(reactor, tahoe, real_reactor, protocolClass):
    server_port = fake_log_server(protocolClass)
    server_addr = server_port.getHost()

    # Make sure the streamed logs websocket client can compute the correct ws
    # url.  If it doesn't match the server, the handshake fails.
    tahoe.nodeurl = "http://{}:{}".format(server_addr.host, server_addr.port)
    tahoe.streamedlogs.start(tahoe.nodeurl, tahoe.api_token)
    _, _, client_factory = reactor.connectTCP.call_args[0]

    endpoint = TCP4ClientEndpoint(
        real_reactor,
        # Windows doesn't like to connect to 0.0.0.0.
        "127.0.0.1" if server_addr.host == "0.0.0.0" else server_addr.host,
        server_addr.port,
    )
    return endpoint.connect(client_factory) 
Example #4
Source File: streamedlogs.py    From gridsync with GNU General Public License v3.0 6 votes vote down vote up
def _create_client_service(self, nodeurl, api_token):
        url = parse(nodeurl)
        wsurl = url.replace(scheme="ws").child("private", "logs", "v1")

        factory = WebSocketClientFactory(
            url=wsurl.to_uri().to_text(),
            headers={
                "Authorization": "{} {}".format("tahoe-lafs", api_token),
            },
        )
        factory.protocol = TahoeLogReader
        factory.streamedlogs = self

        endpoint = TCP4ClientEndpoint(self._reactor, url.host, url.port)
        client_service = ClientService(endpoint, factory, clock=self._reactor)
        return client_service 
Example #5
Source File: test_endpoints.py    From python-for-android with Apache License 2.0 6 votes vote down vote up
def test_tcp(self):
        """
        When passed a TCP strports description, L{endpointClient} 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.assertIdentical(client._reactor, reactor)
        self.assertEquals(client._host, "example.com")
        self.assertEquals(client._port, 1234)
        self.assertEquals(client._timeout, 7)
        self.assertEquals(client._bindAddress, "10.0.0.2") 
Example #6
Source File: test_endpoints.py    From python-for-android with Apache License 2.0 6 votes vote down vote up
def createClientEndpoint(self, reactor, clientFactory, **connectArgs):
        """
        Create an L{TCP4ClientEndpoint} and return the values needed to verify
        its behavior.

        @param reactor: A fake L{IReactorTCP} that L{TCP4ClientEndpoint} can
            call L{IReactorTCP.connectTCP} on.
        @param clientFactory: The thing that we expect to be passed to our
            L{IStreamClientEndpoint.connect} implementation.
        @param connectArgs: Optional dictionary of arguments to
            L{IReactorTCP.connectTCP}
        """
        address = IPv4Address("TCP", "localhost", 80)

        return (endpoints.TCP4ClientEndpoint(reactor,
                                             address.host,
                                             address.port,
                                             **connectArgs),
                (address.host, address.port, clientFactory,
                 connectArgs.get('timeout', 30),
                 connectArgs.get('bindAddress', None)),
                address) 
Example #7
Source File: _hints.py    From magic-wormhole with MIT License 6 votes vote down vote up
def endpoint_from_hint_obj(hint, tor, reactor):
    if tor:
        if isinstance(hint, (DirectTCPV1Hint, TorTCPV1Hint)):
            # this Tor object will throw ValueError for non-public IPv4
            # addresses and any IPv6 address
            try:
                return tor.stream_via(hint.hostname, hint.port)
            except ValueError:
                return None
        return None
    if isinstance(hint, DirectTCPV1Hint):
        # avoid DNS lookup unless necessary
        if isIPAddress(hint.hostname):
            return TCP4ClientEndpoint(reactor, hint.hostname, hint.port)
        if isIPv6Address(hint.hostname):
            return TCP6ClientEndpoint(reactor, hint.hostname, hint.port)
        return HostnameEndpoint(reactor, hint.hostname, hint.port)
    return None 
Example #8
Source File: iosim.py    From learn_python3_spider with MIT License 6 votes vote down vote up
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) 
Example #9
Source File: endpoints.py    From learn_python3_spider with MIT License 6 votes vote down vote up
def secureConnection(self):
        """
        Create and return a new SSH connection which has been secured and on
        which authentication has already happened.

        @return: A L{Deferred} which fires with the ready-to-use connection or
            with a failure if something prevents the connection from being
            setup, secured, or authenticated.
        """
        protocol = _CommandTransport(self)
        ready = protocol.connectionReady

        sshClient = TCP4ClientEndpoint(
            self.reactor, nativeString(self.hostname), self.port)

        d = connectProtocol(sshClient, protocol)
        d.addCallback(lambda ignored: ready)
        return d 
Example #10
Source File: test_endpoints.py    From learn_python3_spider with MIT License 6 votes vote down vote up
def test_connectProtocolCreatesFactory(self):
        """
        C{endpoints.connectProtocol} calls the given endpoint's C{connect()}
        method with a factory that will build the given protocol.
        """
        reactor = MemoryReactor()
        endpoint = endpoints.TCP4ClientEndpoint(reactor, "127.0.0.1", 0)
        theProtocol = object()
        endpoints.connectProtocol(endpoint, theProtocol)

        # A TCP connection was made via the given endpoint:
        self.assertEqual(len(reactor.tcpClients), 1)
        # TCP4ClientEndpoint uses a _WrapperFactory around the underlying
        # factory, so we need to unwrap it:
        factory = reactor.tcpClients[0][2]._wrappedFactory
        self.assertIsInstance(factory, protocol.Factory)
        self.assertIs(factory.buildProtocol(None), theProtocol) 
Example #11
Source File: test_endpoints.py    From learn_python3_spider with MIT License 6 votes vote down vote up
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)) 
Example #12
Source File: graphite.py    From worker with GNU General Public License v3.0 6 votes vote down vote up
def connect(self, reconnecting=False):
        if self.connecting and not reconnecting:
            return
        self.connecting = True
        end_point = TCP4ClientEndpoint(reactor, self.host, self.port, 10)
        d = end_point.connect(Factory.forProtocol(GraphiteProtocol))

        def success(connection):
            self.connecting = False
            log.info('Connected to {replica}', replica=self)
            self.connection = connection

        def failed(error):
            log.error('Connect to {replica} failed: {error}', replica=self, error=error)
            reactor.callLater(10, self.connect, True)
        d.addCallbacks(success, failed) 
Example #13
Source File: test_endpoints.py    From learn_python3_spider with MIT License 6 votes vote down vote up
def createClientEndpoint(self, reactor, clientFactory, **connectArgs):
        """
        Create an L{TCP4ClientEndpoint} and return the values needed to verify
        its behavior.

        @param reactor: A fake L{IReactorTCP} that L{TCP4ClientEndpoint} can
            call L{IReactorTCP.connectTCP} on.
        @param clientFactory: The thing that we expect to be passed to our
            L{IStreamClientEndpoint.connect} implementation.
        @param connectArgs: Optional dictionary of arguments to
            L{IReactorTCP.connectTCP}
        """
        address = IPv4Address("TCP", "localhost", 80)

        return (endpoints.TCP4ClientEndpoint(reactor,
                                             address.host,
                                             address.port,
                                             **connectArgs),
                (address.host, address.port, clientFactory,
                 connectArgs.get('timeout', 30),
                 connectArgs.get('bindAddress', None)),
                address) 
Example #14
Source File: rsc.py    From rscoin with BSD 2-Clause "Simplified" License 6 votes vote down vote up
def broadcast(small_dir, data):
    d_list = []
    responses = []
    # d = defer.Deferred()

    def gotProtocol(p):
        p.sendLine(data)

    for (kid, ip, port) in small_dir:
        _stats[ip] += 1
        point = TCP4ClientEndpoint(reactor, ip, int(port), timeout=10)
        f = RSCfactory()

        d = point.connect(f)
        d.addCallback(gotProtocol)
        d.addErrback(f.d.errback)
        # f.d.errback

        d_list += [ f.d ]

    d_all = defer.gatherResults(d_list)
    return d_all 
Example #15
Source File: iosim.py    From Safejumper-for-Desktop with GNU General Public License v2.0 6 votes vote down vote up
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) 
Example #16
Source File: endpoints.py    From Safejumper-for-Desktop with GNU General Public License v2.0 6 votes vote down vote up
def secureConnection(self):
        """
        Create and return a new SSH connection which has been secured and on
        which authentication has already happened.

        @return: A L{Deferred} which fires with the ready-to-use connection or
            with a failure if something prevents the connection from being
            setup, secured, or authenticated.
        """
        protocol = _CommandTransport(self)
        ready = protocol.connectionReady

        sshClient = TCP4ClientEndpoint(
            self.reactor, nativeString(self.hostname), self.port)

        d = connectProtocol(sshClient, protocol)
        d.addCallback(lambda ignored: ready)
        return d 
Example #17
Source File: test_endpoints.py    From Safejumper-for-Desktop with GNU General Public License v2.0 6 votes vote down vote up
def test_connectProtocolCreatesFactory(self):
        """
        C{endpoints.connectProtocol} calls the given endpoint's C{connect()}
        method with a factory that will build the given protocol.
        """
        reactor = MemoryReactor()
        endpoint = endpoints.TCP4ClientEndpoint(reactor, "127.0.0.1", 0)
        theProtocol = object()
        endpoints.connectProtocol(endpoint, theProtocol)

        # A TCP connection was made via the given endpoint:
        self.assertEqual(len(reactor.tcpClients), 1)
        # TCP4ClientEndpoint uses a _WrapperFactory around the underlying
        # factory, so we need to unwrap it:
        factory = reactor.tcpClients[0][2]._wrappedFactory
        self.assertIsInstance(factory, protocol.Factory)
        self.assertIs(factory.buildProtocol(None), theProtocol) 
Example #18
Source File: test_endpoints.py    From Safejumper-for-Desktop with GNU General Public License v2.0 6 votes vote down vote up
def createClientEndpoint(self, reactor, clientFactory, **connectArgs):
        """
        Create an L{TCP4ClientEndpoint} and return the values needed to verify
        its behavior.

        @param reactor: A fake L{IReactorTCP} that L{TCP4ClientEndpoint} can
            call L{IReactorTCP.connectTCP} on.
        @param clientFactory: The thing that we expect to be passed to our
            L{IStreamClientEndpoint.connect} implementation.
        @param connectArgs: Optional dictionary of arguments to
            L{IReactorTCP.connectTCP}
        """
        address = IPv4Address("TCP", "localhost", 80)

        return (endpoints.TCP4ClientEndpoint(reactor,
                                             address.host,
                                             address.port,
                                             **connectArgs),
                (address.host, address.port, clientFactory,
                 connectArgs.get('timeout', 30),
                 connectArgs.get('bindAddress', None)),
                address) 
Example #19
Source File: test_endpoints.py    From Safejumper-for-Desktop with GNU General Public License v2.0 6 votes vote down vote up
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)) 
Example #20
Source File: test_endpoints.py    From Safejumper-for-Desktop with GNU General Public License v2.0 6 votes vote down vote up
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)) 
Example #21
Source File: amppush.py    From ccs-calendarserver with Apache License 2.0 5 votes vote down vote up
def subscribeToIDs(host, port, ids, callback, reactor=None):
    """
    Clients can call this helper method to register a callback which
    will get called whenever a push notification is fired for any
    id in the ids list.

    @param host: AMP host name to connect to
    @type host: string
    @param port: AMP port to connect to
    @type port: integer
    @param ids: The push IDs to subscribe to
    @type ids: list of strings
    @param callback: The method to call whenever a notification is
        received.
    @type callback: callable which is passed an id (string)
    """

    if reactor is None:
        from twisted.internet import reactor

    token = str(uuid.uuid4())
    endpoint = TCP4ClientEndpoint(reactor, host, port)
    factory = AMPPushClientFactory(callback)
    protocol = yield endpoint.connect(factory)
    for id in ids:
        yield protocol.callRemote(SubscribeToID, token=token, id=id)

    returnValue(factory) 
Example #22
Source File: twisted.py    From kotori with GNU Affero General Public License v3.0 5 votes vote down vote up
def connect(self):
        log.info('Connecting')
        factory = MQTTFactory(profile=MQTTFactory.PUBLISHER | MQTTFactory.SUBSCRIBER)
        point   = TCP4ClientEndpoint(reactor, self.broker_host, self.broker_port)
        d = point.connect(factory).addCallback(self.gotProtocol)
        d.addErrback(self.on_error) 
Example #23
Source File: test_tcp.py    From Safejumper-for-Desktop with GNU General Public License v2.0 5 votes vote down vote up
def client(self, reactor, serverAddress):
        """
        Create a client end point that will connect to the given address.

        @type serverAddress: L{IPv4Address}
        """
        return TCP4ClientEndpoint(reactor, self.interface, serverAddress.port) 
Example #24
Source File: test_txsni.py    From txsni with MIT License 5 votes vote down vote up
def handshake(
        client_factory,
        server_factory,
        hostname,
        server_endpoint,
        acceptable_protocols=None,
):
    """
    Connect a basic Twisted TLS client endpoint to the provided TxSNI
    TLSEndpoint. Returns a Deferred that fires when the connection has been
    established with a tuple of an instance of the client protocol and the
    listening port.
    """
    def connect_client(listening_port):
        port_number = listening_port.getHost().port
        client = endpoints.TCP4ClientEndpoint(
            reactor, '127.0.0.1', port_number
        )

        maybe_alpn = {}
        if acceptable_protocols is not None:
            maybe_alpn['acceptableProtocols'] = acceptable_protocols

        options = optionsForClientTLS(
            hostname=hostname,
            trustRoot=PEM_ROOT,
            **maybe_alpn
        )
        client = endpoints.wrapClientTLS(options, client)
        connectDeferred = client.connect(client_factory)

        def aggregate(client_proto):
            return (client_proto, listening_port)

        connectDeferred.addCallback(aggregate)
        return connectDeferred

    listenDeferred = server_endpoint.listen(server_factory)
    listenDeferred.addCallback(connect_client)
    return listenDeferred 
Example #25
Source File: portscanner.py    From freshonions-torscraper with GNU Affero General Public License v3.0 5 votes vote down vote up
def connect(self):
        torEndpoint = TCP4ClientEndpoint(reactor, TOR_HOST, TOR_PORT)
        proxiedEndpoint = SOCKS5ClientEndpoint(self.active_host.hostname.encode("ascii"), self.current_port, torEndpoint)
        d = proxiedEndpoint.connect(PortScannerClientFactory(self))
        d.addCallback(gotProtocol, self)
        d.addErrback(gotErr, self)
        #reactor.callLater(60, d.cancel) 
Example #26
Source File: irc.py    From joinmarket-clientserver with GNU General Public License v3.0 5 votes vote down vote up
def build_irc(self):
        """The main starting method that creates a protocol object
        according to the config variables, ready for whenever
        the reactor starts running.
        """
        wlog('building irc')
        if self.tx_irc_client:
            raise Exception('irc already built')
        if self.usessl.lower() == 'true':
            ctx = ClientContextFactory()
        if self.usessl.lower() == 'true' and not self.socks5.lower() == 'true':
            factory = TxIRCFactory(self)
            reactor.connectSSL(self.serverport[0], self.serverport[1],
                               factory, ctx)
        elif self.socks5.lower() == 'true':
            factory = TxIRCFactory(self)
            #str() casts needed else unicode error
            torEndpoint = TCP4ClientEndpoint(reactor, str(self.socks5_host),
                                             self.socks5_port)
            if self.usessl.lower() == 'true':
                use_tls = ctx
            else:
                use_tls = False
            ircEndpoint = TorSocksEndpoint(torEndpoint, self.serverport[0],
                                           self.serverport[1], tls=use_tls)
            myRS = ClientService(ircEndpoint, factory)
            myRS.startService()
        else:
            try:
                factory = TxIRCFactory(self)
                wlog('build_irc: ', self.serverport[0], str(self.serverport[1]),
                     self.channel)
                self.tcp_connector = reactor.connectTCP(
                        self.serverport[0], self.serverport[1], factory)
            except Exception as e:
                wlog('error in buildirc: ' + repr(e)) 
Example #27
Source File: test_tensor.py    From tensor with MIT License 5 votes vote down vote up
def test_tcp_riemann(self):

        event = Event('ok', 'sky', 'Sky has not fallen', 1.0, 60.0)

        end = TCP4ClientEndpoint(reactor, "localhost", 5555)
       
        p = yield connectProtocol(end, riemann.RiemannProtocol())

        yield p.sendEvents([event])

        p.transport.loseConnection() 
Example #28
Source File: amphub.py    From ccs-calendarserver with Apache License 2.0 5 votes vote down vote up
def start(cls, hostsAndPorts):
        """
        Instantiates the AMPHub singleton and connects to the hosts.

        @param hostsAndPorts: The hosts and ports to connect to
        @type hostsAndPorts: A list of (hostname, port) tuples
        """

        cls._hub = cls()

        for host, port in hostsAndPorts:
            endpoint = TCP4ClientEndpoint(reactor, host, port)
            factory = AMPPushClientFactory(cls._hub._pushReceived)
            protocol = yield endpoint.connect(factory)
            cls._hub.protocols.append(protocol) 
Example #29
Source File: queue.py    From ccs-twistedextensions with Apache License 2.0 5 votes vote down vote up
def endpoint(self, reactor):
        """
        Create an L{IStreamServerEndpoint} that will talk to the node process
        that is described by this L{NodeInfo}.

        @return: an endpoint that will connect to this host.
        @rtype: L{IStreamServerEndpoint}
        """
        return TCP4ClientEndpoint(reactor, self.hostname, self.port) 
Example #30
Source File: test_endpoints.py    From Safejumper-for-Desktop with GNU General Public License v2.0 5 votes vote down vote up
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)