本文整理汇总了Python中twisted.internet.protocol.ClientFactory.protocol方法的典型用法代码示例。如果您正苦于以下问题:Python ClientFactory.protocol方法的具体用法?Python ClientFactory.protocol怎么用?Python ClientFactory.protocol使用的例子?那么恭喜您, 这里精选的方法代码示例或许可以为您提供帮助。您也可以进一步了解该方法所在类twisted.internet.protocol.ClientFactory
的用法示例。
在下文中一共展示了ClientFactory.protocol方法的15个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的Python代码示例。
示例1: main
# 需要导入模块: from twisted.internet.protocol import ClientFactory [as 别名]
# 或者: from twisted.internet.protocol.ClientFactory import protocol [as 别名]
def main():
P = OptionParser(usage="%prog [-C|-S] <-v> host:port")
P.add_option('-v','--verbose', action='count', default=0,
help='Print more information')
P.add_option('-C','--client', action='store_true', default=True,
dest='dir', help='Act as Client to PSC')
P.add_option('-S','--server', action='store_false', dest='dir',
help='Act as Server to IOC')
vals, args = P.parse_args()
if len(args)<1:
P.usage()
sys.exit(1)
host, _, port = args[0].partition(':')
port = int(port or '6')
logging.basicConfig(level=_V.get(vals.verbose, 0))
if vals.dir:
# Client
log.info('Connect to %s:%u', host, port)
fact = ClientFactory()
fact.protocol = PSCClient
ep = reactor.connectTCP(host, port, fact)
else:
# Server
log.info('Serve from %s:%u', host, port)
fact = Factory()
fact.protocol = PSCServer
ep = reactor.listenTCP(port, fact, interface=host or '')
log.info('Run')
reactor.run()
log.info('Done')
示例2: test_handshake
# 需要导入模块: from twisted.internet.protocol import ClientFactory [as 别名]
# 或者: from twisted.internet.protocol.ClientFactory import protocol [as 别名]
def test_handshake(self):
"""
The TLS handshake is performed when L{TLSMemoryBIOProtocol} is
connected to a transport.
"""
clientFactory = ClientFactory()
clientFactory.protocol = Protocol
clientContextFactory, handshakeDeferred = (
HandshakeCallbackContextFactory.factoryAndDeferred())
wrapperFactory = TLSMemoryBIOFactory(
clientContextFactory, True, clientFactory)
sslClientProtocol = wrapperFactory.buildProtocol(None)
serverFactory = ServerFactory()
serverFactory.protocol = Protocol
serverContextFactory = DefaultOpenSSLContextFactory(certPath, certPath)
wrapperFactory = TLSMemoryBIOFactory(
serverContextFactory, False, serverFactory)
sslServerProtocol = wrapperFactory.buildProtocol(None)
connectionDeferred = loopbackAsync(sslServerProtocol, sslClientProtocol)
# Only wait for the handshake to complete. Anything after that isn't
# important here.
return handshakeDeferred
示例3: test_send_peh_upon_connection
# 需要导入模块: from twisted.internet.protocol import ClientFactory [as 别名]
# 或者: from twisted.internet.protocol.ClientFactory import protocol [as 别名]
def test_send_peh_upon_connection(self):
'''To test client protocol we isloate it from the ClientFactory'''
with patch.object(datetime, 'datetime', Mock(wraps=datetime.datetime)) as patched:
fixed_date = datetime.datetime(2014, 1, 1, 12, 0, 0)
patched.now.return_value = fixed_date
factory = ClientFactory()
factory.comaster = self.comaster
factory.protocol = MaraClientProtocol
proto = factory.buildProtocol(('127.0.0.1', 0))
proto.construct = MaraFrame
# Disable unnesesary behaviour
def stop():
proto.stop()
reactor.stop()
proto.sendPoll = MagicMock(side_effect=stop)
transport = proto_helpers.StringTransport()
proto.makeConnection(transport)
bytes_sent_to_device = transport.value()
result = MaraFrame.parse(bytes_sent_to_device)
self.assertEqual(result.dest, 0xFF)
self.assertEqual(result.source, 2)
# We don't need to check BCC since it's already coded into MaraFrame
self.assertEqual(result.peh, fixed_date)
reactor.run()
# Shuld have stopped
self.assertEqual(self.comaster.update_peh_timestamp.call_count, 1)
self.assertEqual(self.comaster.update_peh_timestamp.call_args[0][0],
fixed_date)
示例4: testGetPolicyFile
# 需要导入模块: from twisted.internet.protocol import ClientFactory [as 别名]
# 或者: from twisted.internet.protocol.ClientFactory import protocol [as 别名]
def testGetPolicyFile(self):
class PolicyRequest(Protocol):
def __init__(self, deffered):
self.done = deffered
def connectionMade(self):
request = "<policy-file-request/>%c" % (0, )
self.transport.write(request)
def dataReceived(self, data):
self.transport.loseConnection()
self.done.callback(data)
d = defer.Deferred()
factory = ClientFactory()
factory.protocol = lambda : PolicyRequest(d)
port = self.listener._realPortNumber
reactor.connectTCP('127.0.0.1', port, factory)
def asserts(received):
policy = (
'<?xml version="1.0"?><!DOCTYPE cross-domain-policy SYSTEM '
'"http://www.macromedia.com/xml/dtds/cross-domain-policy.dtd">'
'<cross-domain-policy><allow-access-from domain="*" '
'to-ports="*" /></cross-domain-policy>')
self.assertEqual(policy, received)
d.addCallback(asserts)
return d
示例5: test_writeSequence
# 需要导入模块: from twisted.internet.protocol import ClientFactory [as 别名]
# 或者: from twisted.internet.protocol.ClientFactory import protocol [as 别名]
def test_writeSequence(self):
"""
Bytes written to L{TLSMemoryBIOProtocol} with C{writeSequence} are
received by the protocol on the other side of the connection.
"""
bytes = "some bytes"
class SimpleSendingProtocol(Protocol):
def connectionMade(self):
self.transport.writeSequence(list(bytes))
clientFactory = ClientFactory()
clientFactory.protocol = SimpleSendingProtocol
clientContextFactory = HandshakeCallbackContextFactory()
wrapperFactory = TLSMemoryBIOFactory(
clientContextFactory, True, clientFactory)
sslClientProtocol = wrapperFactory.buildProtocol(None)
serverProtocol = AccumulatingProtocol(len(bytes))
serverFactory = ServerFactory()
serverFactory.protocol = lambda: serverProtocol
serverContextFactory = DefaultOpenSSLContextFactory(certPath, certPath)
wrapperFactory = TLSMemoryBIOFactory(
serverContextFactory, False, serverFactory)
sslServerProtocol = wrapperFactory.buildProtocol(None)
connectionDeferred = loopbackAsync(sslServerProtocol, sslClientProtocol)
# Wait for the connection to end, then make sure the server received
# the bytes sent by the client.
def cbConnectionDone(ignored):
self.assertEquals("".join(serverProtocol.received), bytes)
connectionDeferred.addCallback(cbConnectionDone)
return connectionDeferred
示例6: test_getLogFiles
# 需要导入模块: from twisted.internet.protocol import ClientFactory [as 别名]
# 或者: from twisted.internet.protocol.ClientFactory import protocol [as 别名]
def test_getLogFiles(self):
"""
The reactor returned by L{loggedReactor} has a C{getLogFiles} method
which returns a L{logstate} instance containing the active and
completed log files tracked by the logging wrapper.
"""
wrapped = ClientFactory()
wrapped.protocol = Discard
reactor = MemoryReactor()
logged = loggedReactor(reactor)
logged.connectTCP('127.0.0.1', 1234, wrapped)
factory = reactor.tcpClients[0][2]
finished = factory.buildProtocol(None)
finished.makeConnection(StringTransport())
finished.dataReceived('finished')
finished.connectionLost(None)
active = factory.buildProtocol(None)
active.makeConnection(StringTransport())
active.dataReceived('active')
logs = logged.getLogFiles()
self.assertEqual(1, len(logs.finished))
self.assertIn('finished', logs.finished[0].getvalue())
self.assertEqual(1, len(logs.active))
self.assertIn('active', logs.active[0].getvalue())
示例7: test_connectTCP
# 需要导入模块: from twisted.internet.protocol import ClientFactory [as 别名]
# 或者: from twisted.internet.protocol.ClientFactory import protocol [as 别名]
def test_connectTCP(self):
"""
Called on the object returned by L{loggedReactor}, C{connectTCP} calls
the wrapped reactor's C{connectTCP} method with the original factory
wrapped in a L{_TrafficLoggingFactory}.
"""
class RecordDataProtocol(Protocol):
def dataReceived(self, data):
self.data = data
proto = RecordDataProtocol()
factory = ClientFactory()
factory.protocol = lambda: proto
reactor = MemoryReactor()
logged = loggedReactor(reactor)
logged.connectTCP('192.168.1.2', 1234, factory, 21, '127.0.0.2')
[(host, port, factory, timeout, bindAddress)] = reactor.tcpClients
self.assertEqual('192.168.1.2', host)
self.assertEqual(1234, port)
self.assertIsInstance(factory, _TrafficLoggingFactory)
self.assertEqual(21, timeout)
self.assertEqual('127.0.0.2', bindAddress)
# Verify that the factory and protocol specified are really being used
protocol = factory.buildProtocol(None)
protocol.makeConnection(None)
protocol.dataReceived("foo")
self.assertEqual(proto.data, "foo")
示例8: test_disconnectWhileProducing
# 需要导入模块: from twisted.internet.protocol import ClientFactory [as 别名]
# 或者: from twisted.internet.protocol.ClientFactory import protocol [as 别名]
def test_disconnectWhileProducing(self):
"""
If C{loseConnection} is called while a producer is registered with the
transport, the connection is closed after the producer is unregistered.
"""
reactor = self.buildReactor()
# For some reason, pyobject/pygtk will not deliver the close
# notification that should happen after the unregisterProducer call in
# this test. The selectable is in the write notification set, but no
# notification ever arrives. Probably for the same reason #5233 led
# win32eventreactor to be broken.
skippedReactors = ["Glib2Reactor", "Gtk2Reactor"]
reactorClassName = reactor.__class__.__name__
if reactorClassName in skippedReactors and platform.isWindows():
raise SkipTest("A pygobject/pygtk bug disables this functionality " "on Windows.")
class Producer:
def resumeProducing(self):
log.msg("Producer.resumeProducing")
self.listen(reactor, ServerFactory.forProtocol(Protocol))
finished = Deferred()
finished.addErrback(log.err)
finished.addCallback(lambda ign: reactor.stop())
class ClientProtocol(Protocol):
"""
Protocol to connect, register a producer, try to lose the
connection, unregister the producer, and wait for the connection to
actually be lost.
"""
def connectionMade(self):
log.msg("ClientProtocol.connectionMade")
self.transport.registerProducer(Producer(), False)
self.transport.loseConnection()
# Let the reactor tick over, in case synchronously calling
# loseConnection and then unregisterProducer is the same as
# synchronously calling unregisterProducer and then
# loseConnection (as it is in several reactors).
reactor.callLater(0, reactor.callLater, 0, self.unregister)
def unregister(self):
log.msg("ClientProtocol unregister")
self.transport.unregisterProducer()
# This should all be pretty quick. Fail the test
# if we don't get a connectionLost event really
# soon.
reactor.callLater(1.0, finished.errback, Failure(Exception("Connection was not lost")))
def connectionLost(self, reason):
log.msg("ClientProtocol.connectionLost")
finished.callback(None)
clientFactory = ClientFactory()
clientFactory.protocol = ClientProtocol
self.connect(reactor, clientFactory)
self.runReactor(reactor)
示例9: writeBeforeHandshakeTest
# 需要导入模块: from twisted.internet.protocol import ClientFactory [as 别名]
# 或者: from twisted.internet.protocol.ClientFactory import protocol [as 别名]
def writeBeforeHandshakeTest(self, sendingProtocol, bytes):
"""
Run test where client sends data before handshake, given the sending
protocol and expected bytes.
"""
clientFactory = ClientFactory()
clientFactory.protocol = sendingProtocol
clientContextFactory, handshakeDeferred = (
HandshakeCallbackContextFactory.factoryAndDeferred())
wrapperFactory = TLSMemoryBIOFactory(
clientContextFactory, True, clientFactory)
sslClientProtocol = wrapperFactory.buildProtocol(None)
serverProtocol = AccumulatingProtocol(len(bytes))
serverFactory = ServerFactory()
serverFactory.protocol = lambda: serverProtocol
serverContextFactory = DefaultOpenSSLContextFactory(certPath, certPath)
wrapperFactory = TLSMemoryBIOFactory(
serverContextFactory, False, serverFactory)
sslServerProtocol = wrapperFactory.buildProtocol(None)
connectionDeferred = loopbackAsync(sslServerProtocol, sslClientProtocol)
# Wait for the connection to end, then make sure the server received
# the bytes sent by the client.
def cbConnectionDone(ignored):
self.assertEqual("".join(serverProtocol.received), bytes)
connectionDeferred.addCallback(cbConnectionDone)
return connectionDeferred
示例10: test_disorderlyShutdown
# 需要导入模块: from twisted.internet.protocol import ClientFactory [as 别名]
# 或者: from twisted.internet.protocol.ClientFactory import protocol [as 别名]
def test_disorderlyShutdown(self):
"""
If a L{TLSMemoryBIOProtocol} loses its connection unexpectedly, this is
reported to the application.
"""
clientConnectionLost = Deferred()
clientFactory = ClientFactory()
clientFactory.protocol = (
lambda: ConnectionLostNotifyingProtocol(
clientConnectionLost))
clientContextFactory = HandshakeCallbackContextFactory()
wrapperFactory = TLSMemoryBIOFactory(
clientContextFactory, True, clientFactory)
sslClientProtocol = wrapperFactory.buildProtocol(None)
# Client speaks first, so the server can be dumb.
serverProtocol = Protocol()
connectionDeferred = loopbackAsync(serverProtocol, sslClientProtocol)
# Now destroy the connection.
serverProtocol.transport.loseConnection()
# And when the connection completely dies, check the reason.
def cbDisconnected(clientProtocol):
clientProtocol.lostConnectionReason.trap(Error)
clientConnectionLost.addCallback(cbDisconnected)
return clientConnectionLost
示例11: getCachedConnection
# 需要导入模块: from twisted.internet.protocol import ClientFactory [as 别名]
# 或者: from twisted.internet.protocol.ClientFactory import protocol [as 别名]
def getCachedConnection(self):
"""
Ask the L{conncache.ConnectionCache} for a connection to the endpoint
created in L{setUp}.
"""
factory = ClientFactory()
factory.protocol = lambda: self.protocol
return self.cache.connectCached(self.endpoint, factory)
示例12: _create_client_factory
# 需要导入模块: from twisted.internet.protocol import ClientFactory [as 别名]
# 或者: from twisted.internet.protocol.ClientFactory import protocol [as 别名]
def _create_client_factory(self, target_id):
factory = ClientFactory()
factory.protocol = OutgoingProtocol
factory.target_id = target_id
factory.add_connection = self.outgoing_connections.add
factory.remove_connection = self.outgoing_connections.remove
self._init_factory(factory)
return factory
示例13: makeProto
# 需要导入模块: from twisted.internet.protocol import ClientFactory [as 别名]
# 或者: from twisted.internet.protocol.ClientFactory import protocol [as 别名]
def makeProto(self, *a, **kw):
protoClass = kw.pop('_protoClass', self.protocol)
fac = ClientFactory(*a, **kw)
fac.protocol = protoClass
proto = fac.buildProtocol(None)
transport = proto_helpers.StringTransport()
transport.abortConnection = lambda: None
proto.makeConnection(transport)
return fac, proto
示例14: connect
# 需要导入模块: from twisted.internet.protocol import ClientFactory [as 别名]
# 或者: from twisted.internet.protocol.ClientFactory import protocol [as 别名]
def connect(self, host, port):
self._connection_timeout = self.timeout
self._stack_conn = _Connection()
self._stack_conn.attach(self)
self._stack_conn.connect_cb = Callback()
factory = ClientFactory()
factory.protocol = lambda: self._stack_conn
factory.clientConnectionFailed = self.clientConnectionFailed
self._connect_to_reactor(host, port, factory, self._connection_timeout)
yield self._stack_conn.connect_cb
示例15: makeProto
# 需要导入模块: from twisted.internet.protocol import ClientFactory [as 别名]
# 或者: from twisted.internet.protocol.ClientFactory import protocol [as 别名]
def makeProto(self, *a, **kw):
protoClass = kw.pop('_protoClass', self.protocol)
fac = ClientFactory(*a, **kw)
fac.protocol = protoClass
def raise_(ex):
raise ex
fac.bobConnectionFailed = lambda reason: raise_(reason)
proto = fac.buildProtocol(None)
transport = proto_helpers.StringTransport()
transport.abortConnection = lambda: None
proto.makeConnection(transport)
return fac, proto