Python twisted.internet.protocol.ClientCreator() Examples

The following are 30 code examples of twisted.internet.protocol.ClientCreator(). 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.protocol , or try the search function .
Example #1
Source File: test_tcp.py    From python-for-android with Apache License 2.0 6 votes vote down vote up
def setUp(self):
        """
        Set up a server and connect a client to it.  Return a Deferred which
        only fires once this is done.
        """
        self.serverFactory = MyHCFactory()
        self.serverFactory.protocolConnectionMade = defer.Deferred()
        self.port = reactor.listenTCP(
            0, self.serverFactory, interface="127.0.0.1")
        self.addCleanup(self.port.stopListening)
        addr = self.port.getHost()
        creator = protocol.ClientCreator(reactor, MyHCProtocol)
        clientDeferred = creator.connectTCP(addr.host, addr.port)
        def setClient(clientProtocol):
            self.clientProtocol = clientProtocol
        clientDeferred.addCallback(setClient)
        return defer.gatherResults([
            self.serverFactory.protocolConnectionMade,
            clientDeferred]) 
Example #2
Source File: test_tcp.py    From learn_python3_spider with MIT License 6 votes vote down vote up
def setUp(self):
        """
        Set up a server and connect a client to it.  Return a Deferred which
        only fires once this is done.
        """
        self.serverFactory = MyHCFactory()
        self.serverFactory.protocolConnectionMade = defer.Deferred()
        self.port = reactor.listenTCP(
            0, self.serverFactory, interface="127.0.0.1")
        self.addCleanup(self.port.stopListening)
        addr = self.port.getHost()
        creator = protocol.ClientCreator(reactor, MyHCProtocol)
        clientDeferred = creator.connectTCP(addr.host, addr.port)
        def setClient(clientProtocol):
            self.clientProtocol = clientProtocol
        clientDeferred.addCallback(setClient)
        return defer.gatherResults([
            self.serverFactory.protocolConnectionMade,
            clientDeferred]) 
Example #3
Source File: test_ftp.py    From learn_python3_spider with MIT License 6 votes vote down vote up
def test_tooManyConnections(self):
        """
        When the connection limit is reached, the server should send an
        appropriate response
        """
        self.factory.connectionLimit = 1
        cc = protocol.ClientCreator(reactor, _BufferingProtocol)
        d = cc.connectTCP("127.0.0.1", self.port.getHost().port)

        @d.addCallback
        def gotClient(proto):
            return proto.d

        @d.addCallback
        def onConnectionLost(proto):
            self.assertEqual(
                b'421 Too many users right now, try again in a few minutes.'
                b'\r\n',
                proto.buffer)

        return d 
Example #4
Source File: test_ftp.py    From Safejumper-for-Desktop with GNU General Public License v2.0 6 votes vote down vote up
def test_tooManyConnections(self):
        """
        When the connection limit is reached, the server should send an
        appropriate response
        """
        self.factory.connectionLimit = 1
        cc = protocol.ClientCreator(reactor, _BufferingProtocol)
        d = cc.connectTCP("127.0.0.1", self.port.getHost().port)

        @d.addCallback
        def gotClient(proto):
            return proto.d

        @d.addCallback
        def onConnectionLost(proto):
            self.assertEqual(
                b'421 Too many users right now, try again in a few minutes.'
                b'\r\n',
                proto.buffer)

        return d 
Example #5
Source File: test_tcp.py    From Safejumper-for-Desktop with GNU General Public License v2.0 6 votes vote down vote up
def setUp(self):
        """
        Set up a server and connect a client to it.  Return a Deferred which
        only fires once this is done.
        """
        self.serverFactory = MyHCFactory()
        self.serverFactory.protocolConnectionMade = defer.Deferred()
        self.port = reactor.listenTCP(
            0, self.serverFactory, interface="127.0.0.1")
        self.addCleanup(self.port.stopListening)
        addr = self.port.getHost()
        creator = protocol.ClientCreator(reactor, MyHCProtocol)
        clientDeferred = creator.connectTCP(addr.host, addr.port)
        def setClient(clientProtocol):
            self.clientProtocol = clientProtocol
        clientDeferred.addCallback(setClient)
        return defer.gatherResults([
            self.serverFactory.protocolConnectionMade,
            clientDeferred]) 
Example #6
Source File: agent.py    From ccs-calendarserver with Apache License 2.0 6 votes vote down vote up
def getList():
    # For the sample client, below:
    from twisted.internet import reactor
    from twisted.internet.protocol import ClientCreator

    creator = ClientCreator(reactor, amp.AMP)
    host = '127.0.0.1'
    import sys
    if len(sys.argv) > 1:
        host = sys.argv[1]
    d = creator.connectTCP(host, 62308)

    def connected(ampProto):
        return ampProto.callRemote(GatewayAMPCommand, command=command)
    d.addCallback(connected)

    def resulted(result):
        return result['result']
    d.addCallback(resulted)

    def done(result):
        print('Done: %s' % (result,))
        reactor.stop()
    d.addCallback(done)
    reactor.run() 
Example #7
Source File: test_ftp.py    From BitTorrent with GNU General Public License v3.0 5 votes vote down vote up
def _makeDataConnection(self, ignored=None):
        # Establish a passive data connection (i.e. client connecting to
        # server).
        d = self.client.queueStringCommand('PASV')
        def gotPASV(responseLines):
            host, port = ftp.decodeHostPort(responseLines[-1][4:])
            cc = protocol.ClientCreator(reactor, _BufferingProtocol)
            return cc.connectTCP('127.0.0.1', port)
        return d.addCallback(gotPASV) 
Example #8
Source File: test_conch.py    From BitTorrent with GNU General Public License v3.0 5 votes vote down vote up
def _connect(self):
        self.connected = 1
        cc = protocol.ClientCreator(reactor, ConchTestForwardingPort, self)
        d = cc.connectTCP('127.0.0.1', self.port)
        d.addErrback(self._ebConnect) 
Example #9
Source File: channels.py    From canvas with BSD 3-Clause "New" or "Revised" License 5 votes vote down vote up
def connect(self):  
        cc = lambda *args: protocol.ClientCreator(reactor, *args)

        self.redis_sub = RedisDispatch(settings.REDIS_HOST, settings.REDIS_PORT)
        redis_factory = RedisServiceRegisteringFactory(self)
        reactor.connectTCP(settings.REDIS_HOST, settings.REDIS_PORT, redis_factory)
        yield redis_factory.deferred 
Example #10
Source File: test_commands.py    From joinmarket-clientserver with GNU General Public License v3.0 5 votes vote down vote up
def setUp(self):
        print("setUp()")
        self.port = reactor.listenTCP(28184, JMTestServerProtocolFactory())
        self.addCleanup(self.port.stopListening)
        def cb(client):
            self.client = client
            self.addCleanup(self.client.transport.loseConnection)
        creator = protocol.ClientCreator(reactor, JMTestClientProtocol)
        creator.connectTCP("localhost", 28184).addCallback(cb) 
Example #11
Source File: tocsupport.py    From BitTorrent with GNU General Public License v3.0 5 votes vote down vote up
def _startLogOn(self, chatui):
        logonDeferred = defer.Deferred()
        cc = protocol.ClientCreator(reactor, TOCProto, self, chatui,
                                    logonDeferred)
        d = cc.connectTCP(self.host, self.port)
        d.addErrback(logonDeferred.errback)
        return logonDeferred 
Example #12
Source File: test_ftp.py    From BitTorrent with GNU General Public License v3.0 5 votes vote down vote up
def setUp(self):
        # Create a directory
        self.directory = self.mktemp()
        os.mkdir(self.directory)

        # Start the server
        p = portal.Portal(ftp.FTPRealm(self.directory))
        p.registerChecker(checkers.AllowAnonymousAccess(), 
                          credentials.IAnonymous)
        self.factory = ftp.FTPFactory(portal=p)
        self.port = reactor.listenTCP(0, self.factory, interface="127.0.0.1")

        # Hook the server's buildProtocol to make the protocol instance
        # accessible to tests.
        buildProtocol = self.factory.buildProtocol
        d1 = defer.Deferred()
        def _rememberProtocolInstance(addr):
            protocol = buildProtocol(addr)
            self.serverProtocol = protocol.wrappedProtocol
            d1.callback(None)
            return protocol
        self.factory.buildProtocol = _rememberProtocolInstance

        # Connect a client to it
        portNum = self.port.getHost().port
        clientCreator = protocol.ClientCreator(reactor, ftp.FTPClientBasic)
        d2 = clientCreator.connectTCP("127.0.0.1", portNum)
        def gotClient(client):
            self.client = client
        d2.addCallback(gotClient)
        return defer.gatherResults([d1, d2]) 
Example #13
Source File: test_pb.py    From BitTorrent with GNU General Public License v3.0 5 votes vote down vote up
def testImmediateClose(self):
        cc = protocol.ClientCreator(reactor, protocol.Protocol)
        d = cc.connectTCP("127.0.0.1", self.portno)
        d.addCallback(lambda p: p.transport.loseConnection())
        d = defer.Deferred()
        # clunky, but it works
        reactor.callLater(0.1, d.callback, None)
        return d


# yay new cred, everyone use this: 
Example #14
Source File: test_tcp.py    From BitTorrent with GNU General Public License v3.0 5 votes vote down vote up
def setUp(self):
        PortCleanerUpper.setUp(self)
        self.f = f = MyHCFactory()
        self.p = p = reactor.listenTCP(0, f, interface="127.0.0.1")
        self.ports.append(p)
        d = loopUntil(lambda :p.connected)
        def connect(ignored):
            c = protocol.ClientCreator(reactor, MyHCProtocol)
            return c.connectTCP(p.getHost().host, p.getHost().port)
        def setClient(client):
            self.client = client
            self.assertEquals(self.client.transport.connected, 1)
        d.addCallback(connect)
        d.addCallback(setClient)
        return d 
Example #15
Source File: test_tcp.py    From BitTorrent with GNU General Public License v3.0 5 votes vote down vote up
def setUp(self):
        self.f = f = MyServerFactory()
        self.f.protocolConnectionMade = defer.Deferred()
        self.p = p = reactor.listenTCP(0, f, interface="127.0.0.1")

        # XXX we don't test server side yet since we don't do it yet
        d = protocol.ClientCreator(reactor, MyProtocol).connectTCP(
            p.getHost().host, p.getHost().port)
        d.addCallback(self._gotClient)
        return d 
Example #16
Source File: forwarding.py    From BitTorrent with GNU General Public License v3.0 5 votes vote down vote up
def channelOpen(self, specificData):
        cc = protocol.ClientCreator(reactor, SSHForwardingClient, self)
        log.msg("connecting to %s:%i" % self.hostport)
        cc.connectTCP(*self.hostport).addCallbacks(self._setClient, self._close) 
Example #17
Source File: toc.py    From BitTorrent with GNU General Public License v3.0 5 votes vote down vote up
def rvous_accept(self,cookie):
        user,uuid,pip,port,d=self._cookies[cookie]
        self.sendFlap(2,"toc_rvous_accept %s %s %s" % (normalize(user),
                                                     cookie,uuid))
        if uuid==SEND_FILE_UID:
            protocol.ClientCreator(reactor, SendFileTransfer,self,cookie,user,d["name"]).connectTCP(pip,port) 
Example #18
Source File: oscar.py    From BitTorrent with GNU General Public License v3.0 5 votes vote down vote up
def connectToBOS(self, server, port):
        c = protocol.ClientCreator(reactor, self.BOSClass, self.username, self.cookie)
        return c.connectTCP(server, int(port)) 
Example #19
Source File: test_ftp.py    From python-for-android with Apache License 2.0 5 votes vote down vote up
def testFailedRETR(self):
        f = protocol.Factory()
        f.noisy = 0
        port = reactor.listenTCP(0, f, interface="127.0.0.1")
        self.addCleanup(port.stopListening)
        portNum = port.getHost().port
        # This test data derived from a bug report by ranty on #twisted
        responses = ['220 ready, dude (vsFTPd 1.0.0: beat me, break me)',
                     # USER anonymous
                     '331 Please specify the password.',
                     # PASS twisted@twistedmatrix.com
                     '230 Login successful. Have fun.',
                     # TYPE I
                     '200 Binary it is, then.',
                     # PASV
                     '227 Entering Passive Mode (127,0,0,1,%d,%d)' %
                     (portNum >> 8, portNum & 0xff),
                     # RETR /file/that/doesnt/exist
                     '550 Failed to open file.']
        f.buildProtocol = lambda addr: PrintLines(responses)

        client = ftp.FTPClient(passive=1)
        cc = protocol.ClientCreator(reactor, ftp.FTPClient, passive=1)
        d = cc.connectTCP('127.0.0.1', portNum)
        def gotClient(client):
            p = protocol.Protocol()
            return client.retrieveFile('/file/that/doesnt/exist', p)
        d.addCallback(gotClient)
        return self.assertFailure(d, ftp.CommandFailed) 
Example #20
Source File: test_ftp.py    From python-for-android with Apache License 2.0 5 votes vote down vote up
def _makeDataConnection(self, ignored=None):
        # Establish a passive data connection (i.e. client connecting to
        # server).
        d = self.client.queueStringCommand('PASV')
        def gotPASV(responseLines):
            host, port = ftp.decodeHostPort(responseLines[-1][4:])
            cc = protocol.ClientCreator(reactor, _BufferingProtocol)
            return cc.connectTCP('127.0.0.1', port)
        return d.addCallback(gotPASV) 
Example #21
Source File: test_tcp.py    From python-for-android with Apache License 2.0 5 votes vote down vote up
def setUp(self):
        self.f = f = MyServerFactory()
        self.f.protocolConnectionMade = defer.Deferred()
        self.p = p = reactor.listenTCP(0, f, interface="127.0.0.1")

        # XXX we don't test server side yet since we don't do it yet
        d = protocol.ClientCreator(reactor, AccumulatingProtocol).connectTCP(
            p.getHost().host, p.getHost().port)
        d.addCallback(self._gotClient)
        return d 
Example #22
Source File: test_tcp.py    From python-for-android with Apache License 2.0 5 votes vote down vote up
def setUp(self):
        self.f = f = MyHCFactory()
        self.p = p = reactor.listenTCP(0, f, interface="127.0.0.1")
        self.addCleanup(p.stopListening)
        d = loopUntil(lambda :p.connected)

        self.cf = protocol.ClientCreator(reactor, MyHCProtocol)

        d.addCallback(lambda _: self.cf.connectTCP(p.getHost().host,
                                                   p.getHost().port))
        d.addCallback(self._setUp)
        return d 
Example #23
Source File: test_tcp.py    From python-for-android with Apache License 2.0 5 votes vote down vote up
def connectClient(self, address, portNumber, clientCreator):
        """
        Establish a connection to the given address using the given
        L{ClientCreator} instance.

        @return: A Deferred which will fire with the connected protocol instance.
        """
        raise NotImplementedError() 
Example #24
Source File: test_conch.py    From python-for-android with Apache License 2.0 5 votes vote down vote up
def _connect(self):
        """
        Connect to the server, which is often a third-party process.
        Tries to reconnect if it fails because we have no way of determining
        exactly when the port becomes available for listening -- we can only
        know when the process starts.
        """
        cc = protocol.ClientCreator(reactor, ConchTestForwardingPort, self,
                                    self.data)
        d = cc.connectTCP('127.0.0.1', self.port)
        d.addErrback(self._ebConnect)
        return d 
Example #25
Source File: default.py    From python-for-android with Apache License 2.0 5 votes vote down vote up
def serviceStarted(self):
        if 'SSH_AUTH_SOCK' in os.environ and not self.options['noagent']:
            log.msg('using agent')
            cc = protocol.ClientCreator(reactor, agent.SSHAgentClient)
            d = cc.connectUNIX(os.environ['SSH_AUTH_SOCK'])
            d.addCallback(self._setAgent)
            d.addErrback(self._ebSetAgent)
        else:
            userauth.SSHUserAuthClient.serviceStarted(self) 
Example #26
Source File: agent.py    From python-for-android with Apache License 2.0 5 votes vote down vote up
def channelOpen(self, specificData):
        cc = protocol.ClientCreator(reactor, SSHAgentForwardingLocal)
        d = cc.connectUNIX(os.environ['SSH_AUTH_SOCK'])
        d.addCallback(self._cbGotLocal)
        d.addErrback(lambda x:self.loseConnection())
        self.buf = '' 
Example #27
Source File: socks.py    From python-for-android with Apache License 2.0 5 votes vote down vote up
def connectClass(self, host, port, klass, *args):
        return protocol.ClientCreator(reactor, klass, *args).connectTCP(host,port) 
Example #28
Source File: test_iocp.py    From python-for-android with Apache License 2.0 5 votes vote down vote up
def test_stopStartReading(self):
        """
        This test checks transport read state! There are three bits
        of it:
        1) The transport producer is paused -- transport.reading
           is False)
        2) The transport is about to schedule an OS read, on the next
           reactor iteration -- transport._readScheduled
        3) The OS has a pending asynchronous read on our behalf --
           transport._readScheduledInOS
        if 3) is not implemented, it is possible to trick IOCPReactor into
        scheduling an OS read before the previous one finishes
        """
        sf = ServerFactory()
        sf.protocol = StopStartReadingProtocol
        sf.ready_d = Deferred()
        sf.stop_d = Deferred()
        p = reactor.listenTCP(0, sf)
        port = p.getHost().port
        cc = ClientCreator(reactor, Protocol)
        def proceed(protos, port):
            log.msg('PROCEEDING WITH THE TESTATHRON')
            self.assert_(protos[0])
            self.assert_(protos[1])
            protos = protos[0][1], protos[1][1]
            protos[0].transport.write(
                    'x' * (2 * protos[0].transport.readBufferSize) +
                    'y' * (2 * protos[0].transport.readBufferSize))
            return sf.stop_d.addCallback(cleanup, protos, port)
        
        def cleanup(data, protos, port):
            self.assert_(data == 'x'*(2*protos[0].transport.readBufferSize)+
                                 'y'*(2*protos[0].transport.readBufferSize),
                                 'did not get the right data')
            return DeferredList([
                    maybeDeferred(protos[0].transport.loseConnection),
                    maybeDeferred(protos[1].transport.loseConnection),
                    maybeDeferred(port.stopListening)])

        return (DeferredList([cc.connectTCP('127.0.0.1', port), sf.ready_d])
                .addCallback(proceed, p)) 
Example #29
Source File: tocsupport.py    From python-for-android with Apache License 2.0 5 votes vote down vote up
def _startLogOn(self, chatui):
        logonDeferred = defer.Deferred()
        cc = protocol.ClientCreator(reactor, TOCProto, self, chatui,
                                    logonDeferred)
        d = cc.connectTCP(self.host, self.port)
        d.addErrback(logonDeferred.errback)
        return logonDeferred 
Example #30
Source File: toc.py    From python-for-android with Apache License 2.0 5 votes vote down vote up
def rvous_accept(self,cookie):
        user,uuid,pip,port,d=self._cookies[cookie]
        self.sendFlap(2,"toc_rvous_accept %s %s %s" % (normalize(user),
                                                     cookie,uuid))
        if uuid==SEND_FILE_UID:
            protocol.ClientCreator(reactor, SendFileTransfer,self,cookie,user,d["name"]).connectTCP(pip,port)