def connect(self, server): self.disconnect() self.server = server if not server: return username = server.getUsername() if not username: username = '******' password = '******' else: password = server.getPassword() host = server.getAddress() passive = server.getPassive() port = server.getPort() timeout = 30 # TODO: make configurable # XXX: we might want to add a guard so we don't try to connect to another host while a previous attempt is not timed out if server.getConnectionType(): try: ftps = ftplib.FTP_TLS() ftps.connect(host,port) ftps.login(username, password) ftps.prot_p() self.controlConnectionMade(ftps) except ftplib.all_errors as e: self.connectionFailed(e) else: creator = ClientCreator(reactor, FTPClient, username, password, passive = passive) creator.connectTCP(host, port, timeout).addCallback(self.controlConnectionMade).addErrback(self.connectionFailed)
def connectionMade(self): c = ClientCreator(reactor,Clienttransfer) host = rs.srandmember('upstream','1')[0] port = 80 print host c.connectTCP(host,port).addCallback(self.set_protocol) self.transport.pauseProducing()
def __init__(self, host, port, path, fileOrName, username = '******', \ password = '******', writeProgress = None, passive = True, \ supportPartial = False, *args, **kwargs): timeout = 30 # We need this later self.path = path self.resume = supportPartial # Initialize self.currentlength = 0 self.totallength = None if writeProgress and type(writeProgress) is not list: writeProgress = [ writeProgress ] self.writeProgress = writeProgress # Output 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()
def sendCommand(command): def test(d): print "Invio ->", command d.sendCommand(command) c = ClientCreator(reactor, Sender) c.connectTCP(HOST, PORT).addCallback(test)
def create_robot(cb): from consts import HOST, PORT from client import AppProtocol from user_manager import request_handler from twisted.internet.protocol import ClientCreator f = ClientCreator(reactor, AppProtocol, request_handler) f.connectTCP(HOST, PORT).addCallback(partial(cb))
def doMath(): creator = ClientCreator(reactor, amp.AMP) sumDeferred = creator.connectTCP('127.0.0.1', 1234) def connected(ampProto): return ampProto.callRemote(Sum, a=13, b=81) sumDeferred.addCallback(connected) def summed(result): return result['total'] sumDeferred.addCallback(summed) divideDeferred = creator.connectTCP('127.0.0.1', 1234) def connected(ampProto): return ampProto.callRemote(Divide, numerator=1234, denominator=0) divideDeferred.addCallback(connected) def trapZero(result): result.trap(ZeroDivisionError) print "Divided by zero: returning INF" return 1e1000 divideDeferred.addErrback(trapZero) def done(result): print 'Done with math:', result reactor.stop() defer.DeferredList([sumDeferred, divideDeferred]).addCallback(done)
def connect(self, server): self.disconnect() self.server = server if not server: return username = server.getUsername() if not username: username = '******' password = '******' else: password = server.getPassword() host = server.getAddress() passive = server.getPassive() port = server.getPort() timeout = 30 # TODO: make configurable # XXX: we might want to add a guard so we don't try to connect to another host while a previous attempt is not timed out creator = ClientCreator(reactor, FTPClient, username, password, passive=passive) creator.connectTCP(host, port, timeout).addCallback( self.controlConnectionMade).addErrback(self.connectionFailed)
def __init__(self, host, port, path, fileOrName, username = '******', \ password = '******', passive = True, supportPartial = False, \ *args, **kwargs): timeout = 30 # We need this later self.path = path self.resume = supportPartial # Output 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()
def __init__(self, host, port, path, fileOrName, username = '******', \ password = '******', writeProgress = None, passive = True, \ supportPartial = False, *args, **kwargs): timeout = 30 # We need this later self.path = path self.resume = supportPartial # Initialize self.currentlength = 0 self.totallength = None if writeProgress and type(writeProgress) is not list: writeProgress = [writeProgress] self.writeProgress = writeProgress # Output 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()
def connectionMade(self): logshow ("connected") # 在不需要工厂时可以直接使用这个类来产生仅使用一次的客户端连接。这时,协议对象之间没有共享状态,也不需要重新连接。 c = ClientCreator(reactor,Clienttransfer) c.connectTCP("192.168.4.2",3389).addCallback(self.set_protocol) #连接并返回refer,设置callback 参数是新protocol,add之后立即callback? self.transport.pauseProducing() # 代理服务暂停数据接收
def collect(self): # Start connecting to carbon first, it's remote... carbon_c = ClientCreator(reactor, CarbonClient) carbon = carbon_c.connectTCP(*self.carbon_addr) munin_c = ClientCreator(reactor, MuninClient) try: munin = yield munin_c.connectTCP(*self.munin_addr) except Exception: log.err("Unable to connect to munin-node") return services = yield munin.do_list() stats = yield munin.collect_metrics(services) munin.do_quit() reverse_name = '.'.join(munin.node_name.split('.')[::-1]) flattened = [] for service, metrics in stats.iteritems(): for metric, (value, timestamp) in metrics.iteritems(): path = 'servers.%s.%s.%s' % (reverse_name, service, metric) flattened.append((path, (timestamp, value))) try: carbon = yield carbon except Exception: log.err("Unable to connect to carbon") return yield carbon.sendStats(flattened) carbon.transport.loseConnection()
def render_POST(self, request): def _renderResponse(response): if isinstance(response, Failure): request.write(json.dumps({'success': False, 'message': response.getErrorMessage()})) else: request.write(json.dumps({'success': True})) request.finish() content = parse_qs(request.content.read()) command = content.get('playlist.add', [None])[0] item = content['item'][0] config_parser = RawConfigParser() config_parser.read(os.path.expanduser("~/.config/smplayer/smplayer.ini")) port = config_parser.getint('instances', 'temp\\autoport') creator = ClientCreator(reactor, SMPlayer, item = item) creator.connectTCP('127.0.0.1', port).addBoth(_renderResponse) request.setHeader('Access-Control-Allow-Origin', '*') request.setHeader('Content-Type', 'application/json') return NOT_DONE_YET
def connect(self, ip, port, type, connectionLost=None): d=self.d=defer.Deferred() logging.info("Connecting "+ip+", port "+str(port)) c = ClientCreator(reactor, GTA_Client_Protocol) c.connectTCP(ip, port).addCallback(self.gotProtocol).addErrback(self.failed_connection) self.connectionLost = connectionLost self.type = type return d
def dataReceived(self, data): # NB: this only receives whole frames; so we will just decode # data as-is. # NB: its cometsession.py:TCPConnectionResource that makes sure # we receive whole frames here. self.logger.debug('dataReceived: data=%r' % data) self.logger.debug('self.outgoingConn is', self.outgoingConn) if self.outgoingConn: # NB: outgoingConn is-a ProxyOutgoingProtocol self.logger.debug("write (out): %r" % data) return self.outgoingConn.transport.write(data) if self.state == "handshake": try: data = data.strip() urlparse.uses_netloc.append("ssl") url = urlparse.urlparse(data) if not url.netloc: ssl = False else: ssl = url.scheme == "ssl" host, port = url.netloc.split(':') port = int(port) self.completedHandshake = True except: self.logger.error("failed to connect on handshake", tb=True) self.transport.write("0" + str(ERRORS['InvalidHandshake'])) self.transport.loseConnection() return peer = self.transport.getPeer() self.fromHost = peer.host self.fromPort = peer.port self.toHost = host self.toPort = port allowed = False for source in config.map['[access]'].get((host, port), []): if source == self.transport.hostHeader or source == '*': allowed = True break if not allowed: self.logger.warn('Unauthorized connect from %r:%d to %r:%d' % (self.fromHost, self.fromPort, self.toHost, self.toPort)) self.transport.write("0" + str(ERRORS['Unauthorized'])) self.transport.loseConnection() return self.logger.access('new connection from %s:%s to %s:%d' % (self.fromHost, self.fromPort, self.toHost, self.toPort)) self.state = 'connecting' client = ClientCreator(reactor, ProxyOutgoingProtocol, self) if ssl: from twisted.internet import ssl client.connectSSL(host, port, ssl.ClientContextFactory()).addErrback(self.errorConnection) else: client.connectTCP(host, port).addErrback(self.errorConnection) # TODO: connect timeout or onConnectFailed handling... else: self.transport.write("0" + str(ERRORS['InvalidHandshake'])) self.state = 'closed' self.transport.loseConnection()
def handle_get_list_response(self, peers, data): print("Got get_list response", self.remote_nodeid) print("Peers", peers) for peer in peers: if list(peer.keys())[0] == HOST_IP: continue c = ClientCreator(reactor, ClientProtocol) c.connectTCP(list(peer.keys())[0], 6000).addCallback(gotPeerTask, data=data)
def sendCommand(): def test(d): print "Begin" d.startFactory() c = ClientCreator(reactor, Sender) send_host = TCP_CONNECTION[SITE_NAME]["agent_server"] send_port = TCP_CONNECTION[SITE_NAME]["tcp_port"] c.connectTCP(send_host, send_port).addCallback(test)
def update(self): creator = ClientCreator(reactor, FTPClient, self.username, self.password, passive=self.passive) creator.connectTCP(self.server, self.port).addCallbacks(self.connection_made, self.on_error)
def setRemoteIpCallback(self, ret = False): if ret: self["text"].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 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 operate(self): if self.d != None: logger.log("PerleActuator", "operated while in activation cycle") return c = ClientCreator(reactor, PerleProtocol, self, self.user, self.password, self.relay) c.connectTCP(self.ip, self.port) self.d = defer.Deferred() return self.d
def receive((errorIndication, errorStatus, errorIndex, varBinds, cbCtx)): if errorIndication or errorStatus: cbCtx.job_info['status'] = ERROR _in=0 _out=0 now = time() for oid, val in varBinds: if oid == (ifHCInOctets + (cbCtx.port_id,)): _in = val elif oid == (ifHCOutOctets + (cbCtx.port_id,)): _out = val else: error('port-octets: receive unknown oid') values = () if cbCtx.job_info['in'] != None: d_in = _in - cbCtx.job_info['in'] if d_in < 0: d_in += 2**64 d_out = _out - cbCtx.job_info['out'] if d_out < 0: d_out += 2**64 d_time = now - cbCtx.job_info['time'] debug('delta in:%s delta time:%s' % ( d_in, d_time)) speed_in = d_in*8/d_time # MBit speed_out = d_out*8/d_time values += ( '%s.ports.%s.octets64.in' % ( cbCtx.host_name, cbCtx.port_name ), speed_in, now), values += ( '%s.ports.%s.octets64.out' % ( cbCtx.host_name, cbCtx.port_name ), speed_out, now), c = ClientCreator(reactor, CarbonProtocol, values) c.connectTCP( cbCtx.carbon_host, cbCtx.carbon_port ).addCallback(lambda p: p.sendMessage()) cbCtx.job_info['in'] = _in cbCtx.job_info['out'] = _out cbCtx.job_info['time'] = now
def checkFTPConnection(self): print("[ChannelsImporter] Checking FTP connection to remote receiver") if not inStandby: self["status"].setText(_("Checking FTP connection to remote receiver")) timeout = 5 self.currentLength = 0 self.total = 0 self.working = True creator = ClientCreator(reactor, FTPClient, config.plugins.ChannelsImporter.username.value, config.plugins.ChannelsImporter.password.value, config.plugins.ChannelsImporter.passive.value) creator.connectTCP(self.getRemoteAddress(), config.plugins.ChannelsImporter.port.value, timeout).addCallback(self.checkConnectionCallback).addErrback(self.checkConnectionErrback)
def checkFTPConnection(self): print "[ChannelsImporter] Checking FTP connection to remote receiver" if not inStandby: self["status"].setText(_("Checking FTP connection to remote receiver")) timeout = 5 self.currentLength = 0 self.total = 0 self.working = True creator = ClientCreator(reactor, FTPClient, config.plugins.ChannelsImporter.username.value, config.plugins.ChannelsImporter.password.value, config.plugins.ChannelsImporter.passive.value) creator.connectTCP(self.getRemoteAddress(), config.plugins.ChannelsImporter.port.value, timeout).addCallback(self.checkConnectionCallback).addErrback(self.checkConnectionErrback)
def run(): password = '******' creator = ClientCreator(reactor, FTPClient, 'kyi', password.strip(), passive=1) creator.connectTCP( '127.0.0.1', 2121).addCallback(connectionMade).addErrback(connectionFailed) reactor.run() # @UndefinedVariable
def node_run(): print('Node run ...') endpoint = TCP4ServerEndpoint(reactor, 6000, interface=cfg.host) endpoint.listen(MyFactory()) endpoint_2 = TCP4ServerEndpoint(reactor, 7000, interface=cfg.host) endpoint_2.listen(APIFactory()) c = ClientCreator(reactor, ClientProtocol) c.connectTCP(BOOTSTRAP_IP, BOOTSTRAP_PORT).addCallback(gotProtocol) reactor.run()
def bootieRecover(self): port = self.getActivePort() if port: if self.getActiveMode() == 'linux': c = ClientCreator(reactor, NovacomRun, None) d = c.connectTCP('localhost', port) d.addCallback(cmd_run, True, '/sbin/tellbootie recover') elif self.getActiveMode() == 'bootie': c = ClientCreator(reactor, NovacomRun, None) d = c.connectTCP('localhost', port) d.addCallback(cmd_bootie_run, 'reset')
class ProxyClient(object): def __init__(self): self.c = ClientCreator(reactor, ProxyProtocol) def connect(self, host, port, url): d = defer.Deferred() # print "opening remote connection to %s:%s" % (host, port) self.c.connectTCP(host, port).addCallback(self.connected, d, host, port, url) return d def connected(self, conn, d, host, port, url): conn.handshake(host, port, url, d)
def run(self): text = str(self.cmd.text()) if text: self.output.clear() if self.gui.getActiveMode() == 'linux': c = ClientCreator(reactor, NovacomRun, self) d = c.connectTCP('localhost', self.port) d.addCallback(cmd_run, True, text) elif self.gui.getActiveMode() == 'bootie': c = ClientCreator(reactor, NovacomRun, self) d = c.connectTCP('localhost', self.port) d.addCallback(cmd_bootie_run, text)
def devices_scan_complete(_): if request is None: # we don't want to send any requests, simply call callback and # be done if callback(None): return self.port.stopListening() self.proxy.stop() finish.callback(None) return cc = ClientCreator(reactor, ClientKatCP) host = self.proxy.port.getHost() cc.connectTCP('localhost', host.port).addCallback(connected)
def __init__(self, host, port, path, fileOrName, username = '******', 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 dataReceived(self, data): # NB: this only receives whole frames; so we will just decode # data as-is. # NB: its cometsession.py:TCPConnectionResource that makes sure # we receive whole frames here. self.logger.debug('dataReceived: data=%r' % data) self.logger.debug('self.outgoingConn is %r', self.outgoingConn) if self.outgoingConn: # NB: outgoingConn is-a ProxyOutgoingProtocol self.logger.debug("write (out): %r" % data) return self.outgoingConn.transport.write(data) if self.state == "handshake": try: data = data.strip() host, port = data.split(':') port = int(port) self.completedHandshake = True except Exception as exc: self.logger.error("failed to connect on handshake") self.transport.write("0" + str(ERRORS['InvalidHandshake'])) self.transport.loseConnection() return peer = self.transport.getPeer() self.fromHost = peer.host self.fromPort = peer.port self.toHost = host self.toPort = port allowed = False for source in config.map['[access]'].get((host, port), []): if source == self.transport.hostHeader or source == '*': allowed = True break if not allowed: self.logger.warn( 'Unauthorized connect from %r:%d to %r:%d' % (self.fromHost, self.fromPort, self.toHost, self.toPort)) self.transport.write("0" + str(ERRORS['Unauthorized'])) self.transport.loseConnection() return self.logger.info( 'new connection from %s:%s to %s:%d' % (self.fromHost, self.fromPort, self.toHost, self.toPort)) self.state = 'connecting' client = ClientCreator(reactor, ProxyOutgoingProtocol, self) client.connectTCP(host, port).addErrback(self.errorConnection) # TODO: connect timeout or onConnectFailed handling... else: self.transport.write("0" + str(ERRORS['InvalidHandshake'])) self.state = 'closed' self.transport.loseConnection()
def run(): # Get config config = Options() config.parseOptions() config.opts['port'] = int(config.opts['port']) config.opts['passive'] = int(config.opts['passive']) config.opts['debug'] = int(config.opts['debug']) # Create the client FTPClient.debug = config.opts['debug'] creator = ClientCreator(reactor, FTPClient, config.opts['username'], config.opts['password'], passive=config.opts['passive']) creator.connectTCP(config.opts['host'], config.opts['port']).addCallback(connectionMade).addErrback(connectionFailed) reactor.run()
class ProxyClient(object): def __init__(self): self.c = ClientCreator(reactor, ProxyProtocol) def connect(self, host, port): d = defer.Deferred() logger.debug("opening remote connection to %s:%s" % (host, port)) self.c.connectTCP(host, port).addCallback(self.connected, d, host, port) return d def connected(self, conn, d, host, port): conn.host, conn.port = host, port d.callback(conn)
def run(num): count = SimulatorLogin.LOGIN_FAIL_COUNT + SimulatorLogin.LOGIN_SUCCESS_COUNT if count < MAX_LOGIN_CLIENT \ and SimulatorLogin.LOGIN_PROCESSING < MAX_LOGIN_QUEUE: user_name = '%s%d' % (USER_NAME, num) nickname = '%s%d' % (NICKNAME, num) print 'add client:', user_name, nickname c = ClientCreator(reactor, SimulatorLogin, user_name, PASSWORD, nickname) c.connectTCP(HOST, PORT) num += 1 reactor.callLater(0, run, num)
def main(reactor): cc = ClientCreator(reactor, AMP) d = cc.connectTCP('localhost', 7805) d.addCallback(otpLogin) d.addCallback(add) d.addCallback(display) return d
def _benchmark(byteCount, clientProtocol): result = {} finished = Deferred() def cbFinished(ignored): result[u'disconnected'] = time() result[u'duration'] = result[u'disconnected'] - result[u'connected'] return result finished.addCallback(cbFinished) f = ServerFactory() f.protocol = lambda: ServerProtocol(byteCount, finished) server = reactor.listenTCP(0, f) f2 = ClientCreator(reactor, clientProtocol) proto = f2.connectTCP('127.0.0.1', server.getHost().port) def connected(proto): result[u'connected'] = time() return proto proto.addCallback(connected) proto.addCallback(_write, byteCount) return finished
def _connect(self, scheme, host, port): """ Connect to the given host and port, using a transport selected based on scheme. @param scheme: A string like C{'http'} or C{'https'} (the only two supported values) to use to determine how to establish the connection. @param host: A C{str} giving the hostname which will be connected to in order to issue a request. @param port: An C{int} giving the port number the connection will be on. @return: A L{Deferred} which fires with a connected instance of C{self._protocol}. """ cc = ClientCreator(self._reactor, self._protocol) if scheme == "http": d = cc.connectTCP(host, port) elif scheme == "https": d = cc.connectSSL(host, port, self._wrapContextFactory(host, port)) else: d = defer.fail(SchemeNotSupported("Unsupported scheme: %r" % (scheme,))) return d
def do_auth(): """Connect and authenticate.""" delegate = TwistedDelegate() spec = load_spec(resource_stream('conn_check', 'amqp0-8.xml')) creator = ClientCreator(reactor, AMQClient, delegate, vhost, spec) client = yield creator.connectTCP(host, port, timeout=timeout) yield client.authenticate(username, password)
def connectToServer(self, host, port, timeout=7): self.elements = [ self.backdrop, ConnectingScreen(self.app, '%s:%s' % (host, port), onCancel=self.cancelConnecting) ] try: cc = ClientCreator(reactor, TrosnothClientProtocol) self.currentDeferred = cc.connectTCP(host, port, timeout=timeout) trosnothClient = yield self.currentDeferred self.trosnothClient = trosnothClient self.currentDeferred = trosnothClient.getSettings() settings = yield self.currentDeferred self.currentDeferred = None self.connectionEstablished(settings) except Exception as e: self.currentDeferred = None self.trosnothClient = None self.elements = [self.backdrop, self.startupInterface] if not isinstance(e, defer.CancelledError): if isinstance(e, ConnectionFailed): text = str(e.reason) else: text = 'Internal Error' log.exception('Unexpected failure in deferred') d = ConnectionFailedDialog(self.app, text) d.show()
def _connect(self, scheme, host, port): """ Connect to the given host and port, using a transport selected based on scheme. @param scheme: A string like C{'http'} or C{'https'} (the only two supported values) to use to determine how to establish the connection. @param host: A C{str} giving the hostname which will be connected to in order to issue a request. @param port: An C{int} giving the port number the connection will be on. @return: A L{Deferred} which fires with a connected instance of C{self._protocol}. """ cc = ClientCreator(self._reactor, self._protocol) if scheme == 'http': d = cc.connectTCP(host, port) elif scheme == 'https': d = cc.connectSSL(host, port, self._wrapContextFactory(host, port)) else: d = defer.fail( SchemeNotSupported("Unsupported scheme: %r" % (scheme, ))) return d
def download_request(self, request, spider): parsed_url = urlparse(request.url) creator = ClientCreator(reactor, FTPClient, request.meta["ftp_user"], request.meta["ftp_password"], passive=request.meta.get("ftp_passive", 1)) return creator.connectTCP(parsed_url.hostname, parsed_url.port or 21).addCallback(self.gotClient, request, parsed_url.path)
def run(self): delegate = TwistedDelegate() cc = ClientCreator(reactor, AMQClient, delegate=delegate, vhost=self.vhost, spec=self.specfile) connection = yield cc.connectTCP(self.host, self.port) yield connection.authenticate(self.user, self.password) channel = yield connection.channel(1) yield channel.channel_open() channel.queue_declare(queue="process_queue", durable=True) # yield channel.queue_bind( # queue="process_queue", exchange="worker", # routing_key="test_routing_key") yield channel.basic_consume(queue="process_queue", consumer_tag="test_consumer_tag", no_ack=True) queue = yield connection.queue("test_consumer_tag") while True: pkg = yield queue.get() msg = pickle.loads(pkg.content.body) print msg self.reply(channel, msg)
def get_forecast(forecast_id): """ Retrieve a text weather forecast from the Australian Bureau of Meteorology FTP server for the city specified by the forecast id. Returns a deferred to the caller that will eventually return the forecast string. @param forecast_id: The forecast city identifier. For example Adelaide is IDS10034, Sydney is IDN10064, etc. @return: A deferred that returns the forecast string or None @rtype: defer.Deferred """ creator = ClientCreator(reactor, FTPClient, username="******", password="******") try: ftpClient = yield creator.connectTCP(BomFtpHost, BomFtpPort) bufferProtocol = BufferingProtocol() forecast_path = BomFtpForecastPath % (forecast_id) _result = yield ftpClient.retrieveFile(forecast_path, bufferProtocol) forecast = bufferProtocol.buffer.getvalue() forecast = forecast.replace("\r", "") # prefer \n as line delimiters logging.debug("Forecast retrieval successful") try: _result = yield ftpClient.quit() except Exception, ex: logging.error("ftpClient failed to quit properly") logging.exception(ex) defer.returnValue(forecast)
def StartTalking(self, identifier_from, name_from, identifier_to, name_to): # currently on wx loop # move it to the twisted loop # fetch host and port for that id creator = ClientCreator(reactor, HydrusServerAMP.MessagingClientProtocol) deferred = creator.connectTCP(host, port) # deferred is called with the connection, or an error # callRemote to register identifier_from and name_from as temp login # then add to temp_connections self._temporary_connections[(identifier_from, name_from, identifier_to, name_to)] = connection message = '' # this is just to get the OTR handshake going; it'll never be sent connection.callRemote(HydrusServerAMP.IMMessageServer, identifier_to=identifier_to, name_to=name_to, message=message)
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()
def connect_client_ivt_to_uni_main(call_uuid=None): global HOST, PORT cc = ClientCreator(reactor, ClientProtocol) df = cc.connectTCP(HOST, PORT) df.addCallback(client_connect_success, call_uuid=call_uuid) df.addErrback(client_connect_fail) return df
def writeMetric(metric_path, value, timestamp, host, port, username, password, vhost, exchange, spec=None, channel_number=1, ssl=False): if not spec: spec = txamqp.spec.load(os.path.normpath( os.path.join(os.path.dirname(__file__), 'amqp0-8.xml'))) delegate = TwistedDelegate() connector = ClientCreator(reactor, AMQClient, delegate=delegate, vhost=vhost, spec=spec) if ssl: from twisted.internet.ssl import ClientContextFactory conn = yield connector.connectSSL(host, port, ClientContextFactory()) else: conn = yield connector.connectTCP(host, port) yield conn.authenticate(username, password) channel = yield conn.channel(channel_number) yield channel.channel_open() yield channel.exchange_declare(exchange=exchange, type="topic", durable=True, auto_delete=False) message = Content( "%f %d" % (value, timestamp) ) message["delivery mode"] = 2 channel.basic_publish(exchange=exchange, content=message, routing_key=metric_path) yield channel.channel_close()
def do_connect(): """Connect and authenticate.""" client_creator = ClientCreator(reactor, MemCacheProtocol) client = yield client_creator.connectTCP(host=host, port=port, timeout=timeout) version = yield client.version()
def connectToGameServer(self, host, port, timeout=5): cc = ClientCreator(reactor, TrosnothClientProtocol) trosnothClient = yield cc.connectTCP(host, port, timeout=timeout) settings = yield trosnothClient.getSettings() defer.returnValue((trosnothClient, settings))
def main(reactor): cc = ClientCreator(reactor, AMP) d = cc.connectTCP('localhost', 7805) d.addCallback(login, UsernamePassword("testuser", "examplepass")) d.addCallback(add) d.addCallback(display) return d
def handle_handshake(self, decoded): if 'login' not in decoded: self.send_error_msg("No login specified") return self.username = decoded['login'] if 'password' not in decoded: self.send_error_msg("No password specified") return self.password = decoded['password'] if 'pool' not in decoded: self.send_error_msg("No pool specified") return pool = decoded['pool'] try: self.pool_address, port_str = pool.split(":") self.pool_port = int(port_str) except: self.send_error_msg("Error when parsing pool information") return self.prn("Opening bridge to %s:%d" % (self.pool_address, self.pool_port)) c = ClientCreator(reactor, StratumClient) d = c.connectTCP(self.pool_address, self.pool_port) d.addCallback(self.pool_got_connection)
def connect_start(self): if self.verbose: print 'connect_start' assert self.chat_state == self.NOT_CONNECTED self.connect_sem = defer.Deferred() creator = ClientCreator(reactor, self.Proxy) d = creator.connectTCP(self.host, self.port) d.addCallback(self.connect_finish) d.addErrback(self.handle_remote_error) self.chat_state = self.CONNECTING