コード例 #1
0
	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)
コード例 #2
0
 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()
コード例 #3
0
	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()
コード例 #4
0
ファイル: client-2.py プロジェクト: sorryone/baofeng_server
def sendCommand(command):
    def test(d):
        print "Invio ->", command
        d.sendCommand(command)

    c = ClientCreator(reactor, Sender)
    c.connectTCP(HOST, PORT).addCallback(test)
コード例 #5
0
ファイル: admin.py プロジェクト: TTXDM/firstGame
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))
コード例 #6
0
def sendCommand(command):
    def test(d):
        print "Invio ->", command
        d.sendCommand(command)

    c = ClientCreator(reactor, Sender)
    c.connectTCP(HOST, PORT).addCallback(test)
コード例 #7
0
ファイル: ampclient.py プロジェクト: enmand/twisted
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)
コード例 #8
0
    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)
コード例 #9
0
    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()
コード例 #10
0
    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()
コード例 #11
0
    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() # 代理服务暂停数据接收
コード例 #12
0
ファイル: client.py プロジェクト: stefanor/txmunin-graphite
    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()
コード例 #13
0
ファイル: smploxy.py プロジェクト: RushOnline/smploxy
    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
コード例 #14
0
ファイル: RemoteClient.py プロジェクト: op07n/crujisim
 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
コード例 #15
0
ファイル: proxy.py プロジェクト: mattbennett/orbited
    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()
コード例 #16
0
 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)
コード例 #17
0
ファイル: client.py プロジェクト: allisnone/letusgo
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)
コード例 #18
0
 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)
コード例 #19
0
	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)
コード例 #20
0
ファイル: plugin.py プロジェクト: OpenLD/enigma2
	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)
コード例 #21
0
ファイル: actuators.py プロジェクト: derfred/doord
    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
コード例 #22
0
ファイル: portoctets64.py プロジェクト: hizel/twistsnmp
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
コード例 #23
0
	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)
コード例 #24
0
	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)
コード例 #25
0
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
コード例 #26
0
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()
コード例 #27
0
ファイル: novatool.py プロジェクト: wosigh/novatool
 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')
コード例 #28
0
ファイル: websocket.py プロジェクト: rp14838/django-orbited
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)
コード例 #29
0
ファイル: novatool.py プロジェクト: wosigh/novatool
 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)
コード例 #30
0
ファイル: test_proxy.py プロジェクト: telegraphic/hipsr_core
 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)
コード例 #31
0
ファイル: FTPDownloader.py プロジェクト: OpenLD/enigma2
 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
コード例 #32
0
 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)
コード例 #33
0
    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()
コード例 #34
0
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()
コード例 #35
0
ファイル: proxy.py プロジェクト: becky2014/django-orbited
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)
コード例 #36
0
ファイル: simulator.py プロジェクト: Cuick/traversing
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)
コード例 #37
0
def main(reactor):
    cc = ClientCreator(reactor, AMP)
    d = cc.connectTCP('localhost', 7805)
    d.addCallback(otpLogin)
    d.addCallback(add)
    d.addCallback(display)
    return d
コード例 #38
0
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
コード例 #39
0
ファイル: client.py プロジェクト: rolando-contribute/cyclone
    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
コード例 #40
0
ファイル: checks.py プロジェクト: tomwardill/conn-check
 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)
コード例 #41
0
    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()
コード例 #42
0
    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
コード例 #43
0
ファイル: ftp.py プロジェクト: 611953/scrapy
 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)
コード例 #44
0
 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)
コード例 #45
0
ファイル: amp_auth_client.py プロジェクト: palfrey/epsilon
def main(reactor):
    cc = ClientCreator(reactor, AMP)
    d = cc.connectTCP('localhost', 7805)
    d.addCallback(otpLogin)
    d.addCallback(add)
    d.addCallback(display)
    return d
コード例 #46
0
    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)
コード例 #47
0
ファイル: forecasts.py プロジェクト: claws/txBOM
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)
コード例 #48
0
    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)
コード例 #49
0
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()
コード例 #50
0
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
コード例 #51
0
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()
コード例 #52
0
ファイル: checks.py プロジェクト: mariusionescu/conn-check
    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()
コード例 #53
0
    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))
コード例 #54
0
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
コード例 #55
0
ファイル: bridge.py プロジェクト: mygirl8893/turtle-webminer
    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)
コード例 #56
0
 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