本文整理匯總了Python中twisted.internet.reactor.connectTCP方法的典型用法代碼示例。如果您正苦於以下問題:Python reactor.connectTCP方法的具體用法?Python reactor.connectTCP怎麽用?Python reactor.connectTCP使用的例子?那麽, 這裏精選的方法代碼示例或許可以為您提供幫助。您也可以進一步了解該方法所在類twisted.internet.reactor
的用法示例。
在下文中一共展示了reactor.connectTCP方法的15個代碼示例,這些例子默認根據受歡迎程度排序。您可以為喜歡或者感覺有用的代碼點讚,您的評價將有助於係統推薦出更棒的Python代碼示例。
示例1: main
# 需要導入模塊: from twisted.internet import reactor [as 別名]
# 或者: from twisted.internet.reactor import connectTCP [as 別名]
def main():
hostname = raw_input('IMAP4 Server Hostname: ')
port = raw_input('IMAP4 Server Port (the default is 143): ')
username = raw_input('IMAP4 Username: ')
password = util.getPassword('IMAP4 Password: ')
onConn = defer.Deferred(
).addCallback(cbServerGreeting, username, password
).addErrback(ebConnection
).addBoth(cbClose)
factory = SimpleIMAP4ClientFactory(username, onConn)
from twisted.internet import reactor
conn = reactor.connectTCP(hostname, int(port), factory)
reactor.run()
示例2: buildProtocol
# 需要導入模塊: from twisted.internet import reactor [as 別名]
# 或者: from twisted.internet.reactor import connectTCP [as 別名]
def buildProtocol(self, addr):
log.debug("%s: New connection from %s:%d." % (self.name, log.safe_addr_str(addr.host), addr.port))
circuit = Circuit(self.transport_class())
# XXX instantiates a new factory for each client
clientFactory = StaticDestinationClientFactory(circuit, self.mode)
if self.pt_config.proxy:
create_proxy_client(self.remote_host, self.remote_port,
self.pt_config.proxy,
clientFactory)
else:
reactor.connectTCP(self.remote_host, self.remote_port, clientFactory)
return StaticDestinationProtocol(circuit, self.mode, addr)
示例3: render
# 需要導入模塊: from twisted.internet import reactor [as 別名]
# 或者: from twisted.internet.reactor import connectTCP [as 別名]
def render(self, request):
"""Render this request, from my server.
This will always be asynchronous, and therefore return NOT_DONE_YET.
It spins off a request to the pb client, and either adds it to the list
of pending issues or requests it immediately, depending on if the
client is already connected.
"""
if not self.publisher:
self.pending.append(request)
if not self.waiting:
self.waiting = 1
bf = pb.PBClientFactory()
timeout = 10
if self.host == "unix":
reactor.connectUNIX(self.port, bf, timeout)
else:
reactor.connectTCP(self.host, self.port, bf, timeout)
d = bf.getRootObject()
d.addCallbacks(self.connected, self.notConnected)
else:
i = Issue(request)
self.publisher.callRemote('request', request).addCallbacks(i.finished, i.failed)
return server.NOT_DONE_YET
示例4: _connect
# 需要導入模塊: from twisted.internet import reactor [as 別名]
# 或者: from twisted.internet.reactor import connectTCP [as 別名]
def _connect(self, method, *args, **kwargs):
"""
Initiate a connection attempt.
@param method: A callable which will actually start the connection
attempt. For example, C{reactor.connectTCP}.
@param *args: Positional arguments to pass to C{method}, excluding the
factory.
@param **kwargs: Keyword arguments to pass to C{method}.
@return: A L{Deferred} which fires with an instance of the protocol
class passed to this L{ClientCreator}'s initializer or fails if the
connection cannot be set up for some reason.
"""
def cancelConnect(deferred):
connector.disconnect()
if f.pending is not None:
f.pending.cancel()
d = defer.Deferred(cancelConnect)
f = _InstanceFactory(
self.reactor, self.protocolClass(*self.args, **self.kwargs), d)
connector = method(factory=f, *args, **kwargs)
return d
示例5: _cbExchange
# 需要導入模塊: from twisted.internet import reactor [as 別名]
# 或者: from twisted.internet.reactor import connectTCP [as 別名]
def _cbExchange(self, address, port, factory):
"""
Initiate a connection with a mail exchange server.
This callback function runs after mail exchange server for the domain
has been looked up.
@type address: L{bytes}
@param address: The hostname of a mail exchange server.
@type port: L{int}
@param port: A port number.
@type factory: L{SMTPManagedRelayerFactory}
@param factory: A factory which can create a relayer for the mail
exchange server.
"""
from twisted.internet import reactor
reactor.connectTCP(address, port, factory)
示例6: test_serverRepr
# 需要導入模塊: from twisted.internet import reactor [as 別名]
# 或者: from twisted.internet.reactor import connectTCP [as 別名]
def test_serverRepr(self):
"""
Check that the repr string of the server transport get the good port
number if the server listens on 0.
"""
server = MyServerFactory()
serverConnMade = server.protocolConnectionMade = defer.Deferred()
port = reactor.listenTCP(0, server)
self.addCleanup(port.stopListening)
client = MyClientFactory()
clientConnMade = client.protocolConnectionMade = defer.Deferred()
connector = reactor.connectTCP("127.0.0.1",
port.getHost().port, client)
self.addCleanup(connector.disconnect)
def check(result):
serverProto, clientProto = result
portNumber = port.getHost().port
self.assertEqual(
repr(serverProto.transport),
"<AccumulatingProtocol #0 on %s>" % (portNumber,))
serverProto.transport.loseConnection()
clientProto.transport.loseConnection()
return defer.gatherResults([serverConnMade, clientConnMade]
).addCallback(check)
示例7: test_directConnectionLostCall
# 需要導入模塊: from twisted.internet import reactor [as 別名]
# 或者: from twisted.internet.reactor import connectTCP [as 別名]
def test_directConnectionLostCall(self):
"""
If C{connectionLost} is called directly on a port object, it succeeds
(and doesn't expect the presence of a C{deferred} attribute).
C{connectionLost} is called by L{reactor.disconnectAll} at shutdown.
"""
serverFactory = MyServerFactory()
port = reactor.listenTCP(0, serverFactory, interface="127.0.0.1")
portNumber = port.getHost().port
port.connectionLost(None)
client = MyClientFactory()
serverFactory.protocolConnectionMade = defer.Deferred()
client.protocolConnectionMade = defer.Deferred()
reactor.connectTCP("127.0.0.1", portNumber, client)
def check(ign):
client.reason.trap(error.ConnectionRefusedError)
return client.failDeferred.addCallback(check)
示例8: test_closePortInProtocolFactory
# 需要導入模塊: from twisted.internet import reactor [as 別名]
# 或者: from twisted.internet.reactor import connectTCP [as 別名]
def test_closePortInProtocolFactory(self):
"""
A port created with L{IReactorTCP.listenTCP} can be connected to with
L{IReactorTCP.connectTCP}.
"""
f = ClosingFactory()
port = reactor.listenTCP(0, f, interface="127.0.0.1")
f.port = port
self.addCleanup(f.cleanUp)
portNumber = port.getHost().port
clientF = MyClientFactory()
reactor.connectTCP("127.0.0.1", portNumber, clientF)
def check(x):
self.assertTrue(clientF.protocol.made)
self.assertTrue(port.disconnected)
clientF.lostReason.trap(error.ConnectionDone)
return clientF.deferred.addCallback(check)
示例9: _connectedClientAndServerTest
# 需要導入模塊: from twisted.internet import reactor [as 別名]
# 或者: from twisted.internet.reactor import connectTCP [as 別名]
def _connectedClientAndServerTest(self, callback):
"""
Invoke the given callback with a client protocol and a server protocol
which have been connected to each other.
"""
serverFactory = MyServerFactory()
serverConnMade = defer.Deferred()
serverFactory.protocolConnectionMade = serverConnMade
port = reactor.listenTCP(0, serverFactory, interface="127.0.0.1")
self.addCleanup(port.stopListening)
portNumber = port.getHost().port
clientF = MyClientFactory()
clientConnMade = defer.Deferred()
clientF.protocolConnectionMade = clientConnMade
reactor.connectTCP("127.0.0.1", portNumber, clientF)
connsMade = defer.gatherResults([serverConnMade, clientConnMade])
def connected(result):
serverProtocol, clientProtocol = result
callback(serverProtocol, clientProtocol)
serverProtocol.transport.loseConnection()
clientProtocol.transport.loseConnection()
connsMade.addCallback(connected)
return connsMade
示例10: test_tcpNoDelay
# 需要導入模塊: from twisted.internet import reactor [as 別名]
# 或者: from twisted.internet.reactor import connectTCP [as 別名]
def test_tcpNoDelay(self):
"""
The transport of a protocol connected with L{IReactorTCP.connectTCP} or
L{IReactor.TCP.listenTCP} can have its I{TCP_NODELAY} state inspected
and manipulated with L{ITCPTransport.getTcpNoDelay} and
L{ITCPTransport.setTcpNoDelay}.
"""
def check(serverProtocol, clientProtocol):
for p in [serverProtocol, clientProtocol]:
transport = p.transport
self.assertEqual(transport.getTcpNoDelay(), 0)
transport.setTcpNoDelay(1)
self.assertEqual(transport.getTcpNoDelay(), 1)
transport.setTcpNoDelay(0)
self.assertEqual(transport.getTcpNoDelay(), 0)
return self._connectedClientAndServerTest(check)
示例11: testWriter
# 需要導入模塊: from twisted.internet import reactor [as 別名]
# 或者: from twisted.internet.reactor import connectTCP [as 別名]
def testWriter(self):
f = protocol.Factory()
f.protocol = LargeBufferWriterProtocol
f.done = 0
f.problem = 0
f.len = self.datalen
wrappedF = FireOnCloseFactory(f)
p = reactor.listenTCP(0, wrappedF, interface="127.0.0.1")
self.addCleanup(p.stopListening)
n = p.getHost().port
clientF = LargeBufferReaderClientFactory()
wrappedClientF = FireOnCloseFactory(clientF)
reactor.connectTCP("127.0.0.1", n, wrappedClientF)
d = defer.gatherResults([wrappedF.deferred, wrappedClientF.deferred])
def check(ignored):
self.assertTrue(f.done, "writer didn't finish, it probably died")
self.assertTrue(clientF.len == self.datalen,
"client didn't receive all the data it expected "
"(%d != %d)" % (clientF.len, self.datalen))
self.assertTrue(clientF.done,
"client didn't see connection dropped")
return d.addCallback(check)
示例12: setUp
# 需要導入模塊: from twisted.internet import reactor [as 別名]
# 或者: from twisted.internet.reactor import connectTCP [as 別名]
def setUp(self):
"""
Create a pb server using L{CachedReturner} protocol and connect a
client to it.
"""
self.orig = NewStyleCacheCopy()
self.orig.s = "value"
self.server = reactor.listenTCP(0,
ConnectionNotifyServerFactory(CachedReturner(self.orig)))
clientFactory = pb.PBClientFactory()
reactor.connectTCP("localhost", self.server.getHost().port,
clientFactory)
def gotRoot(ref):
self.ref = ref
d1 = clientFactory.getRootObject().addCallback(gotRoot)
d2 = self.server.factory.connectionMade
return gatherResults([d1, d2])
示例13: test_NSP
# 需要導入模塊: from twisted.internet import reactor [as 別名]
# 或者: from twisted.internet.reactor import connectTCP [as 別名]
def test_NSP(self):
"""
An L{IPerspective} implementation which does not subclass
L{Avatar} can expose remote methods for the client to call.
"""
factory = pb.PBClientFactory()
d = factory.login(credentials.UsernamePassword(b'user', b'pass'),
"BRAINS!")
reactor.connectTCP('127.0.0.1', self.portno, factory)
d.addCallback(lambda p: p.callRemote('ANYTHING', 'here', bar='baz'))
d.addCallback(self.assertEqual,
('ANYTHING', ('here',), {'bar': 'baz'}))
def cleanup(ignored):
factory.disconnect()
for p in self.factory.protocols:
p.transport.loseConnection()
d.addCallback(cleanup)
return d
示例14: received_broadcast
# 需要導入模塊: from twisted.internet import reactor [as 別名]
# 或者: from twisted.internet.reactor import connectTCP [as 別名]
def received_broadcast(self, data):
print "Received feed."
message = Message(data)
row = db.select_entries("contacts", {"label": message.label})
if len(row) == 0:
print "Can't find this label: " + message.label
return
row = row[0]
message.decrypt(row["sharedkey"])
if not message.validate():
print "Received an invalid message."
return
print "Found label: " + message.label
if self.factory.role == "hidden-client":
if self.factory.listener_factory:
self.factory.listener_factory.send_message(message.cleartext_msg)
self.factory.listener_factory.client.transport.loseConnection()
db.insert_entry("contacts", {"name": self.factory.name, "label":message.new_label, "sharedkey": row["sharedkey"]})
else:
if self.factory.role == "proxy":
message.cleartext_msg = re.sub(r'CONNECT (?P<value>.*?) HTTP/1.0\r\n', 'CONNECT localhost HTTP/1.0\r\n', message.cleartext_msg)
socks_client_factory = HTTPClientFactory(reactor, message)
socks_client_factory.set_communicator(self)
reactor.connectTCP("localhost", 4333, socks_client_factory)
db.insert_entry("contacts", {"name": self.factory.name, "label":message.new_label, "sharedkey": row["sharedkey"]})
示例15: daemon_main
# 需要導入模塊: from twisted.internet import reactor [as 別名]
# 或者: from twisted.internet.reactor import connectTCP [as 別名]
def daemon_main(name, role, server):
#parser = argparse.ArgumentParser(description='bar-daemon')
#parser.add_argument('--name', default=False, help='Label of contact')
#parser.add_argument('--role', default=False, help='Role of client')
#args = parser.parse_args()
#name = name or args.name
#role = role or args.role
communicator_factory = CommunicatorFactory(reactor, name, role)
if role == "hidden-client":
listener_factory = ListenerFactory(reactor, communicator_factory)
communicator_factory.set_listener(listener_factory)
port = reactor.listenTCP(4333, listener_factory,
interface="127.0.0.1")
else:
port = reactor.listenTCP(4333, ProxyFactory())
print "Starting reactor..."
reactor.connectTCP(server, 231, communicator_factory)
print 'Listening on %s.' % (port.getHost())
reactor.run()