本文整理汇总了Python中twisted.internet.endpoints.connectProtocol函数的典型用法代码示例。如果您正苦于以下问题:Python connectProtocol函数的具体用法?Python connectProtocol怎么用?Python connectProtocol使用的例子?那么恭喜您, 这里精选的函数代码示例或许可以为您提供帮助。
在下文中一共展示了connectProtocol函数的20个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于我们的系统推荐出更棒的Python代码示例。
示例1: process
def process(self):
parsed = urllib_parse.urlparse(self.uri)
protocol = parsed[0]
host = parsed[1].decode('ascii')
if protocol in self.ports:
port = self.ports[protocol]
else:
# handle
pass
if ':' in host:
host, port = host.split(':')
port = int(port)
rest = urllib_parse.urlunparse((b'', b'') + parsed[2:])
if not rest:
rest = rest + b'/'
if protocol in self.protocols:
factory = self.protocols[protocol]
headers = self.getAllHeaders().copy()
if b'host' not in headers:
headers[b'host'] = host.encode('ascii')
headers.pop(b'user-agent', None)
headers[b'user-agent'] = b'I2P'
self.content.seek(0, 0)
s = self.content.read()
client = factory(self.method, rest, self.clientproto, headers, s, self)
ep = self.endpointFactory(host, port)
connectProtocol(ep, client.buildProtocol(ep))
开发者ID:majestrate,项目名称:i2p-tools,代码行数:32,代码来源:http.py
示例2: doMath
def doMath():
destination = TCP4ClientEndpoint(reactor, "127.0.0.1", 1234)
sumDeferred = connectProtocol(destination, AMP())
def connected(ampProto):
return ampProto.callRemote(Sum, a=13, b=81)
sumDeferred.addCallback(connected)
def summed(result):
return result["total"]
sumDeferred.addCallback(summed)
divideDeferred = connectProtocol(destination, AMP())
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)
开发者ID:samsoft00,项目名称:careervacancy,代码行数:33,代码来源:ampclient.py
示例3: test_basic
def test_basic(self):
ep = clientFromString(reactor, self.transit)
a1 = yield connectProtocol(ep, Accumulator())
a2 = yield connectProtocol(ep, Accumulator())
token1 = b"\x00"*32
a1.transport.write(b"please relay " + hexlify(token1) + b"\n")
a2.transport.write(b"please relay " + hexlify(token1) + b"\n")
# a correct handshake yields an ack, after which we can send
exp = b"ok\n"
yield a1.waitForBytes(len(exp))
self.assertEqual(a1.data, exp)
s1 = b"data1"
a1.transport.write(s1)
exp = b"ok\n"
yield a2.waitForBytes(len(exp))
self.assertEqual(a2.data, exp)
# all data they sent after the handshake should be given to us
exp = b"ok\n"+s1
yield a2.waitForBytes(len(exp))
self.assertEqual(a2.data, exp)
a1.transport.loseConnection()
a2.transport.loseConnection()
开发者ID:dreid,项目名称:magic-wormhole,代码行数:27,代码来源:test_server.py
示例4: range_check
def range_check(self, firstbyte, lastbyte, setset=False):
test_deferred = Deferred()
self._logger.debug("range_test: %s %s %s setset %s", firstbyte, lastbyte, self.sourcesize, setset)
if firstbyte is not None and lastbyte is None:
exp_byte_range = (firstbyte, self.sourcesize - 1)
elif firstbyte is None and lastbyte is not None:
exp_byte_range = (self.sourcesize - lastbyte, self.sourcesize - 1)
else:
exp_byte_range = (firstbyte, lastbyte)
# the amount of bytes actually requested. (Content-length)
self.expsize = exp_byte_range[1] - exp_byte_range[0] + 1
f = open(self.sourcefn, "rb")
f.seek(exp_byte_range[0])
expdata = f.read(self.expsize)
f.close()
def on_connected(p):
p.sendMessage(self.get_header(firstbyte, lastbyte, setset))
endpoint = TCP4ClientEndpoint(reactor, "localhost", self.port)
connectProtocol(endpoint, VideoServerProtocol(test_deferred, self.sourcesize, expdata, setset, exp_byte_range))\
.addCallback(on_connected)
return test_deferred
开发者ID:synctext,项目名称:tribler,代码行数:26,代码来源:test_video_server.py
示例5: on_deploy_start
def on_deploy_start(self):
now = int(time.time())
events = ("events.deploy.%s %d %d\r\n" % (component, 1, now)
for component in self.components)
message = "".join(events)
protocol = OneShotMessageWriter(message)
endpoint = endpoints.clientFromString(reactor, self.endpoint_config)
endpoints.connectProtocol(endpoint, protocol)
开发者ID:dellis23,项目名称:rollingpin,代码行数:9,代码来源:graphite.py
示例6: start_client
def start_client(proto):
client_endpoint = TCP4ClientEndpoint(reactor, 'localhost', 1234)
nickname = 'PyClient' + str(random.getrandbits(23))
factory = PyClientProtocolFactory(nickname)
proto = factory.buildProtocol(('localhost', 0))
connectProtocol(client_endpoint, proto)
d = Deferred()
reactor.callLater(4, d.callback, proto)
d.addCallback(test_state)
return d
开发者ID:FlorianWilhelm,项目名称:pokerthproto,代码行数:10,代码来源:test_proxy.py
示例7: connectionMade
def connectionMade(self):
script_dir = os.getcwd()
rel_path = "hostkeys"
abs_file_path = os.path.join(script_dir, rel_path)
knownHosts = KnownHostsFile.fromPath(abs_file_path)
self.point = SSHCommandClientEndpoint.newConnection(reactor, 'cmd', 'user', '127.0.0.1', port=5122,
password='password', knownHosts=PermissiveKnownHosts())
self.sshSide = FzSSHClient()
self.sshSide.tcpSide = self
connectProtocol(self.point, self.sshSide)
开发者ID:matanmaz,项目名称:SshTelnetProxy,代码行数:10,代码来源:TcpSshConverter.py
示例8: perform_run
def perform_run(dispatcher, intent):
context.bind(
message_type="flocker.provision.ssh:run",
command=intent.log_command_filter(intent.command),
).write()
endpoint = SSHCommandClientEndpoint.existingConnection(
connection, intent.command)
d = Deferred()
connectProtocol(endpoint, CommandProtocol(
deferred=d, context=context))
return d
开发者ID:wangbinxiang,项目名称:flocker,代码行数:11,代码来源:_conch.py
示例9: onEvent
def onEvent(self, ev):
if ev.getName() == YowNetworkLayer.EVENT_STATE_CONNECT:
# self.create_socket(socket.AF_INET, socket.SOCK_STREAM)
# self.out_buffer = bytearray()
endpoint = self.getProp(YowNetworkLayer.PROP_ENDPOINT)
point = TCP4ClientEndpoint(reactor, endpoint[0], endpoint[1])
connectProtocol(point, self)
# self.connect(endpoint)
return True
elif ev.getName() == YowNetworkLayer.EVENT_STATE_DISCONNECT:
self.handle_close(ev.getArg("reason") or "Requested")
return True
开发者ID:a-d-j-i,项目名称:yowsup,代码行数:12,代码来源:layer.py
示例10: _connectServer
def _connectServer(self, hostname, port, server_queue, client_queue):
"""A helper function for connecting to (hostname, port)
with the given server and client queues.
:param str hostname:
:param int port:
:param DeferredQueue server_queue:
:param DeferredQueue client_queue:
"""
endpoint = TCP4ClientEndpoint(reactor, hostname, port)
protocol = ServerProtocol(
server_queue, client_queue)
connectProtocol(endpoint, protocol)
开发者ID:naphatkrit,项目名称:TigerHost,代码行数:13,代码来源:spoof_tcp_proxy.py
示例11: run
def run(messagehandler):
options = optionsForClientTLS(
hostname=AUTHORITY,
acceptableProtocols=[b'h2', b'http/1.1'],
)
connectProtocol(
SSL4ClientEndpoint(reactor, AUTHORITY, 443, options),
H2Protocol(messagehandler)
)
reactor.run(installSignalHandlers=0)
开发者ID:pbsugg,项目名称:http2-frame-visualizer,代码行数:13,代码来源:twisted_runner.py
示例12: connectServer
def connectServer(self, hostname, port):
"""Tell the proxy what the end server is and start the connection.
The messages in `self.client_queue` will automatically be consumed.
This method should only be called once.
:param str hostname:
:param int port:
"""
endpoint = TCP4ClientEndpoint(reactor, hostname, port)
protocol = ServerProtocol(
self.server_queue, self.client_queue)
connectProtocol(endpoint, protocol)
开发者ID:naphatkrit,项目名称:TigerHost,代码行数:14,代码来源:tcp_proxy.py
示例13: main
def main(reactor=reactor):
arguments = vars(parser.parse_args())
endpoint = clientFromString(
reactor=reactor,
description=arguments["endpoint"],
)
lines = iter(replay_file(arguments["queries"]))
client = BenchmarkClient()
client.lineiterator = lines
connectProtocol(endpoint, client).addCallback(
lambda protocol : protocol.sendLine(lines.next()),
)
reactor.run()
开发者ID:smartkiwi,项目名称:HuntingWabbits,代码行数:15,代码来源:client.py
示例14: main
def main(reactor, args):
endpoint_str = args.endpoint
e = clientFromString(reactor, endpoint_str)
d = connectProtocol(e, LDAPClient())
d.addCallback(onConnect, args)
d.addErrback(onError)
return d
开发者ID:GrayAn,项目名称:ldaptor,代码行数:7,代码来源:client_paged_search_results.py
示例15: run
def run(reactor, command, **kwargs):
"""
Run a process and kill it if the reactor stops.
:param reactor: Reactor to use.
:param list command: The command to run.
:return Deferred: Deferred that fires when the process is ended.
"""
if 'env' not in kwargs:
kwargs['env'] = os.environ
endpoint = ProcessEndpoint(reactor, command[0], command, **kwargs)
protocol_done = Deferred()
protocol = CommandProtocol(deferred=protocol_done, output=sys.stdout)
connected = connectProtocol(endpoint, protocol)
def unregister_killer(result, trigger_id):
try:
reactor.removeSystemEventTrigger(trigger_id)
except:
# If we can't remove the trigger, presumably it has already been
# removed (or run). In any case, there is nothing sensible to do
# if this fails.
pass
return result
def register_killer(_):
trigger_id = reactor.addSystemEventTrigger(
'before', 'shutdown', protocol.transport.signalProcess, 'TERM')
protocol_done.addBoth(unregister_killer, trigger_id)
connected.addCallback(register_killer)
connected.addCallback(lambda _: protocol_done)
return connected
开发者ID:ALSEDLAH,项目名称:flocker,代码行数:35,代码来源:runner.py
示例16: zkconnected
def zkconnected(z, reactor):
val, meta = yield z.get('/brokers/topics/test/partitions/0/state')
broker = json.loads(val)['isr'][0]
val, meta = yield z.get('/brokers/ids/%d' % (broker, ))
val = json.loads(val)
host, port = val['host'], val['port']
ep = TCP4ClientEndpoint(reactor, host, port)
proto = KafkaClientProtocol()
yield connectProtocol(ep, proto)
brokers, topics = yield proto.sender.metadataRequest(topicNames=['test'])
log.debug('Brokers: {brokers!r}', brokers=brokers)
test_zero_md = topics['test'][0]
leader, replicas, isr = test_zero_md
r = yield proto.sender.fetchRequest(replicaId=-1,
maxWaitTime=10,
minBytes=0,
topics=[
('test', [(0, 0, 65535)])
])
r = yield proto.sender.produceRequest(1, 1000, [
('test', [
(0, [
(3, Message(value='message 4'))
])
])
])
开发者ID:tehasdf,项目名称:txkafka,代码行数:29,代码来源:txkafka.py
示例17: makeConnection
def makeConnection(ip, port, connectCallback):
connection = Connection()
connection.callback = connectCallback
point = TCP4ClientEndpoint(reactor, ip, port)
d = connectProtocol(point, connection)
thread.start_new_thread(startConnection, ())
return connection
开发者ID:caithagoras,项目名称:onedir,代码行数:7,代码来源:Connection+-+Admin.py
示例18: main
def main(reactor, args):
vhost = args.vhost
user = args.user
passwd_file = args.passwd_file
if passwd_file is None:
passwd = 'guest'
else:
passwd = passwd_file.read().rstrip("\n\r")
passwd_file.close()
spec_path = os.path.join(
os.path.dirname(__file__),
'spec/amqp0-9-1.stripped.xml')
spec = txamqp.spec.load(spec_path)
params = {
'creds': (user, passwd),
'exchange': args.exchange,
'content': args.msg_file.read(),
'route_key': args.route_key,
}
endpoint_s = args.endpoint
e = clientFromString(reactor, endpoint_s)
delegate = TwistedDelegate()
amqp_protocol = AMQClient(
delegate=delegate,
vhost=vhost,
spec=spec)
d = connectProtocol(e, amqp_protocol)
d.addCallback(on_amqp_connect, params)
return d
开发者ID:cwaldbieser,项目名称:txamqp_tools,代码行数:29,代码来源:txqproducer.py
示例19: connect
def connect(self):
"""Connect client."""
if self.number < self.req_num:
# pre-add the available connection count
# will be decremented if failure occurs
self.number += 1
connector = ClientConnector(self)
# connect through Tor if required, direct connection otherwise
if self.socksproxy:
proxy = random.choice(self.socksproxy)
# Further settings and check
socks_point = TCP4ClientEndpoint(reactor, proxy[0], proxy[1])
point = SOCKS5Point(self.host, self.port, socks_point)
elif self.obfs_level == 3:
meek_point = TCP4ClientEndpoint(
reactor, "127.0.0.1", self.ptproxy_local_port)
point = SOCKS4Point(self.host, self.port, meek_point)
else:
point = TCP4ClientEndpoint(reactor, self.host, self.port)
deferred = connectProtocol(point, connector)
# trigger success or failure action depending on the result
deferred.addCallback(self.success)
deferred.addErrback(lambda ignored: self.retry())
开发者ID:CheckMySoul,项目名称:arkc-server,代码行数:27,代码来源:control.py
示例20: connect
def connect(self, endpoint):
if self.client:
raise RuntimeError("Already connected to %s" % (self.client,))
if self._connecting:
raise RuntimeError("Connection already in progress.")
self._connecting = connectProtocol(endpoint, self._protocolClass())
self._connecting.addCallbacks(self._setClient, self._connectFailed)
开发者ID:RachelLader,项目名称:txOpenBCI,代码行数:7,代码来源:control.py
注:本文中的twisted.internet.endpoints.connectProtocol函数示例由纯净天空整理自Github/MSDocs等源码及文档管理平台,相关代码片段筛选自各路编程大神贡献的开源项目,源码版权归原作者所有,传播和使用请参考对应项目的License;未经允许,请勿转载。 |
请发表评论