本文整理汇总了Python中twisted.internet.protocol.ClientCreator.connectTCP方法的典型用法代码示例。如果您正苦于以下问题:Python ClientCreator.connectTCP方法的具体用法?Python ClientCreator.connectTCP怎么用?Python ClientCreator.connectTCP使用的例子?那么恭喜您, 这里精选的方法代码示例或许可以为您提供帮助。您也可以进一步了解该方法所在类twisted.internet.protocol.ClientCreator
的用法示例。
在下文中一共展示了ClientCreator.connectTCP方法的15个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的Python代码示例。
示例1: render_POST
# 需要导入模块: from twisted.internet.protocol import ClientCreator [as 别名]
# 或者: from twisted.internet.protocol.ClientCreator import connectTCP [as 别名]
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
示例2: sendCommand
# 需要导入模块: from twisted.internet.protocol import ClientCreator [as 别名]
# 或者: from twisted.internet.protocol.ClientCreator import connectTCP [as 别名]
def sendCommand(command):
def test(d):
print "Invio ->", command
d.sendCommand(command)
c = ClientCreator(reactor, Sender)
c.connectTCP(HOST, PORT).addCallback(test)
示例3: collect
# 需要导入模块: from twisted.internet.protocol import ClientCreator [as 别名]
# 或者: from twisted.internet.protocol.ClientCreator import connectTCP [as 别名]
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()
示例4: __init__
# 需要导入模块: from twisted.internet.protocol import ClientCreator [as 别名]
# 或者: from twisted.internet.protocol.ClientCreator import connectTCP [as 别名]
def __init__(self, host, port, path, fileOrName, username = 'anonymous', \
password = '[email protected]', 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()
示例5: connectionMade
# 需要导入模块: from twisted.internet.protocol import ClientCreator [as 别名]
# 或者: from twisted.internet.protocol.ClientCreator import connectTCP [as 别名]
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() # 代理服务暂停数据接收
示例6: connect
# 需要导入模块: from twisted.internet.protocol import ClientCreator [as 别名]
# 或者: from twisted.internet.protocol.ClientCreator import connectTCP [as 别名]
def connect(self, server):
self.disconnect()
self.server = server
if not server:
return
username = server.getUsername()
if not username:
username = 'anonymous'
password = '[email protected]'
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)
示例7: create_robot
# 需要导入模块: from twisted.internet.protocol import ClientCreator [as 别名]
# 或者: from twisted.internet.protocol.ClientCreator import connectTCP [as 别名]
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))
示例8: dataReceived
# 需要导入模块: from twisted.internet.protocol import ClientCreator [as 别名]
# 或者: from twisted.internet.protocol.ClientCreator import connectTCP [as 别名]
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()
示例9: sendCommand
# 需要导入模块: from twisted.internet.protocol import ClientCreator [as 别名]
# 或者: from twisted.internet.protocol.ClientCreator import connectTCP [as 别名]
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)
示例10: setRemoteIpCallback
# 需要导入模块: from twisted.internet.protocol import ClientCreator [as 别名]
# 或者: from twisted.internet.protocol.ClientCreator import connectTCP [as 别名]
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)
示例11: operate
# 需要导入模块: from twisted.internet.protocol import ClientCreator [as 别名]
# 或者: from twisted.internet.protocol.ClientCreator import connectTCP [as 别名]
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
示例12: receive
# 需要导入模块: from twisted.internet.protocol import ClientCreator [as 别名]
# 或者: from twisted.internet.protocol.ClientCreator import connectTCP [as 别名]
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
示例13: checkFTPConnection
# 需要导入模块: from twisted.internet.protocol import ClientCreator [as 别名]
# 或者: from twisted.internet.protocol.ClientCreator import connectTCP [as 别名]
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)
示例14: bootieRecover
# 需要导入模块: from twisted.internet.protocol import ClientCreator [as 别名]
# 或者: from twisted.internet.protocol.ClientCreator import connectTCP [as 别名]
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')
示例15: run
# 需要导入模块: from twisted.internet.protocol import ClientCreator [as 别名]
# 或者: from twisted.internet.protocol.ClientCreator import connectTCP [as 别名]
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)