我们从Python开源项目中,提取了以下45个代码示例,用于说明如何使用twisted.internet.protocol.ClientCreator()。
def startService(self): params = {} if self.settings.get("username", None, section='amqp') \ and self.settings.get("pass", None, section='amqp'): params['credentials'] = pika_credentials.PlainCredentials( self.settings.get("username", None, section='amqp'), self.settings.get("pass", None, section='amqp') ) if self.settings.getdict("params", dict(), section='amqp'): params.update(self.settings.getdict("params", dict(), section='amqp')) if self.settings.get("amqp_vhost", '/'): params.update({'virtual_host': self.settings.get("vhost", '/', section='amqp')}) parameters = ConnectionParameters(**params) self._client = protocol.ClientCreator( reactor, twisted_connection.TwistedProtocolConnection, parameters) self.do_connect()
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])
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
def _startLogOn(self, chatui): logonDeferred = defer.Deferred() cc = protocol.ClientCreator(reactor, IRCProto, self, chatui, logonDeferred) d = cc.connectTCP(self.host, self.port) d.addErrback(logonDeferred.errback) return logonDeferred
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)
def oscar_01_05(self, snac, d = None): """ data for a new service connection d might be a deferred to be called back when the service is ready """ tlvs = readTLVs(snac[3][2:]) service = struct.unpack('!H',tlvs[0x0d])[0] ip = tlvs[5] cookie = tlvs[6] #c = serviceClasses[service](self, cookie, d) c = protocol.ClientCreator(reactor, serviceClasses[service], self, cookie, d) def addService(x): self.services[service] = x c.connectTCP(ip, 5190).addCallback(addService) #self.services[service] = c
def connectToBOS(self, server, port): c = protocol.ClientCreator(reactor, self.BOSClass, self.username, self.cookie) return c.connectTCP(server, int(port))
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 = ''
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)
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)
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()
def test_properlyCloseFiles(self): """ Test that lost connections properly have their underlying socket resources cleaned up. """ onServerConnectionLost = defer.Deferred() serverFactory = protocol.ServerFactory() serverFactory.protocol = lambda: ConnectionLostNotifyingProtocol( onServerConnectionLost) serverPort = self.createServer('127.0.0.1', 0, serverFactory) onClientConnectionLost = defer.Deferred() serverAddr = serverPort.getHost() clientCreator = protocol.ClientCreator( reactor, lambda: HandleSavingProtocol(onClientConnectionLost)) clientDeferred = self.connectClient( serverAddr.host, serverAddr.port, clientCreator) def clientConnected(client): """ Disconnect the client. Return a Deferred which fires when both the client and the server have received disconnect notification. """ client.transport.loseConnection() return defer.gatherResults([ onClientConnectionLost, onServerConnectionLost]) clientDeferred.addCallback(clientConnected) def clientDisconnected((client, server)): """ Verify that the underlying platform socket handle has been cleaned up. """ expectedErrorCode = self.getHandleErrorCode() err = self.assertRaises( self.getHandleExceptionType(), client.handle.send, 'bytes') self.assertEqual(err.args[0], expectedErrorCode)
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
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
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])
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)
def __init__(self, host, port, path, fileOrName, username = 'root', password = '', passive = True, supportPartial = False, *args, **kwargs): timeout = 30 self.path = path self.resume = supportPartial if isinstance(fileOrName, str): self.filename = fileOrName self.file = None else: self.file = fileOrName creator = ClientCreator(reactor, FTPClient, username, password, passive=passive) creator.connectTCP(host, port, timeout).addCallback(self.controlConnectionMade).addErrback(self.connectionFailed) self.deferred = defer.Deferred() return
def setRemoteIpCallback(self, ret = False): if ret: self['statusbar'].setText(_('Testing remote connection')) timeout = 3000 self.currentLength = 0 self.total = 0 self.working = True creator = ClientCreator(reactor, FTPClient, config.plugins.RemoteStreamConverter.username.value, config.plugins.RemoteStreamConverter.password.value, config.plugins.RemoteStreamConverter.passive.value) creator.connectTCP(self.getRemoteAdress(), config.plugins.RemoteStreamConverter.port.value, timeout).addCallback(self.controlConnectionMade).addErrback(self.connectionFailed)
def connectClass( self, host: str, port: int, klass: Type[protocol.Protocol], *args ) -> Any: return protocol.ClientCreator(reactor, klass, *args).connectTCP(host, port)
def connectRequested(self, addr, port): self.transport.stopReading() self.state = STATE_CONNECT_PENDING if isinstance(addr, int): addr = Int2IP(addr) return protocol.ClientCreator(reactor, SOCKSv5Outgoing, self).connectTCP(addr, port)
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)
def downloadFile(self, treeView, path, column): model = treeView.get_model() iter = model.get_iter(path) filename = model.get(iter, 0)[0] h = hashlib.sha1() h.update(filename) key = h.digest() def getTargetNode(result): targetNodeID = result[key] df = self.node.findContact(targetNodeID) return df def getFile(protocol): if protocol != None: protocol.requestFile(filename, self) def connectToPeer(contact): if contact == None: dialog = gtk.MessageDialog(self, gtk.DIALOG_MODAL | gtk.DIALOG_DESTROY_WITH_PARENT, gtk.MESSAGE_ERROR, gtk.BUTTONS_OK, "File could not be retrieved.\nThe host that published this file is no longer on-line.") dialog.run() dialog.destroy() else: c = ClientCreator(twisted.internet.reactor, FileGetter) df = c.connectTCP(contact.address, contact.port) return df df = self.node.iterativeFindValue(key) df.addCallback(getTargetNode) df.addCallback(connectToPeer) df.addCallback(getFile)
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
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
def _makeDataConnection(self, ignored=None): """ Establish a passive data connection (i.e. client connecting to server). @param ignored: ignored @return: L{Deferred.addCallback} """ 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)