本文整理汇总了Python中twisted.internet.protocol.ClientFactory类的典型用法代码示例。如果您正苦于以下问题:Python ClientFactory类的具体用法?Python ClientFactory怎么用?Python ClientFactory使用的例子?那么恭喜您, 这里精选的类代码示例或许可以为您提供帮助。
在下文中一共展示了ClientFactory类的20个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于我们的系统推荐出更棒的Python代码示例。
示例1: testGetPolicyFile
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
开发者ID:kowalski,项目名称:txWebSocket,代码行数:32,代码来源:test_websocket.py
示例2: test_handshake
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
开发者ID:Almad,项目名称:twisted,代码行数:27,代码来源:test_tls.py
示例3: main
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')
开发者ID:mdavidsaver,项目名称:pscdrv,代码行数:35,代码来源:pscsim.py
示例4: test_disorderlyShutdown
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
开发者ID:Almad,项目名称:twisted,代码行数:29,代码来源:test_tls.py
示例5: test_writeSequence
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
开发者ID:Almad,项目名称:twisted,代码行数:35,代码来源:test_tls.py
示例6: test_getLogFiles
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())
开发者ID:eventable,项目名称:CalendarServer,代码行数:27,代码来源:test_trafficlogger.py
示例7: test_connectTCP
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")
开发者ID:eventable,项目名称:CalendarServer,代码行数:27,代码来源:test_trafficlogger.py
示例8: testRetr
def testRetr(self):
# Connect
client = ftp.FTPClient(passive=self.passive)
factory = ClientFactory()
factory.noisy = 0
factory.buildProtocol = lambda s, c=client: c
reactor.connectTCP('localhost', self.ftp_port, factory)
# download ftp_crap
proto = BufferingProtocol()
d = client.retr(os.path.basename('ftp_crap'), proto)
d.addCallbacks(self.callback, self.errback)
# Wait for a result
id = reactor.callLater(5, self.errback, "timed out") # timeout so we don't freeze
while not hasattr(self, 'result') and not hasattr(self, 'error'):
reactor.iterate()
try:
id.cancel()
except ValueError: pass
error = getattr(self, 'error', None)
if error:
raise error[0], error[1], error[2]
# Check that the file is the same as read directly off the disk
self.failUnless(type(self.result) == types.ListType,
'callback result is wrong type: ' + str(self.result))
data = proto.buf.getvalue()
self.failUnless(data == open('ftp_crap', "rb").read(),
'RETRieved file does not match original')
开发者ID:fxia22,项目名称:ASM_xf,代码行数:33,代码来源:test_ftp.py
示例9: testStor
def testStor(self):
# Connect
client = ftp.FTPClient(passive=self.passive)
client.debug = 1
factory = ClientFactory()
factory.noisy = 0
factory.buildProtocol = lambda s, c=client: c
reactor.connectTCP('localhost', self.ftp_port, factory)
expectedContent = "Hello\n"*4
def gotResult(c):
c.write(expectedContent)
c.finish()
def gotErr(f):
self.errback(f)
t = client.storeFile("HelloThere")
t[0].addCallbacks(gotResult, gotErr)
t[1].addCallbacks(self.callback, self.errback)
# Wait for a result
id = reactor.callLater(5, self.errback, "timed out") # timeout so we don't freeze
while not hasattr(self, 'result') and not hasattr(self, 'error'):
reactor.iterate()
try:
id.cancel()
except ValueError: pass
error = getattr(self, 'error', None)
if error:
raise error[0], error[1], error[2]
self.assertEquals(open('HelloThere').read(), expectedContent)
开发者ID:fxia22,项目名称:ASM_xf,代码行数:35,代码来源:test_ftp.py
示例10: testShortFileListings
def testShortFileListings(self):
# Connect
client = ftp.FTPClient(passive=self.passive)
factory = ClientFactory()
factory.noisy = 0
factory.buildProtocol = lambda s, c=client: c
reactor.connectTCP('localhost', self.ftp_port, factory)
# Issue the command and set the callbacks
p = BufferingProtocol()
d = client.nlst('.', p)
d.addCallbacks(self.callback, self.errback)
# Wait for the result
id = reactor.callLater(5, self.errback, "timed out") # timeout so we don't freeze
while not hasattr(self, 'result') and not hasattr(self, 'error'):
reactor.iterate()
try:
id.cancel()
except ValueError: pass
error = getattr(self, 'error', None)
if error:
raise error[0], error[1], error[2]
# Check that the listing contains this file (ftp_crap)
filenames = p.buf.getvalue().split('\r\n')
self.failUnless('ftp_crap' in filenames,
'ftp_crap not in file listing')
开发者ID:fxia22,项目名称:ASM_xf,代码行数:30,代码来源:test_ftp.py
示例11: test_disconnectWhileProducing
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)
开发者ID:samsoft00,项目名称:careervacancy,代码行数:60,代码来源:connectionmixins.py
示例12: writeBeforeHandshakeTest
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
开发者ID:bluemutedwisdom,项目名称:twisted,代码行数:31,代码来源:test_tls.py
示例13: test_send_peh_upon_connection
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)
开发者ID:D3f0,项目名称:txscada,代码行数:35,代码来源:test_protocol_peh.py
示例14: clientConnectionLost
def clientConnectionLost(self, connector, unused_reason):
self.clientProxy.nodeLocator.remove(self.address)
if hasattr(self, 'deferred') and not self.deferred.called:
self.reactor.callLater(0, self.deferred.errback, unused_reason)
del self.deferred
ClientFactory.clientConnectionLost(
self, connector, unused_reason)
开发者ID:dpnova,项目名称:txmemcache,代码行数:7,代码来源:client.py
示例15: getCachedConnection
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)
开发者ID:derwolfe,项目名称:vertex,代码行数:8,代码来源:test_conncache.py
示例16: makeProto
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
开发者ID:mikalv,项目名称:txi2p,代码行数:9,代码来源:test_protocol.py
示例17: _create_client_factory
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
开发者ID:ceronman,项目名称:pixtream,代码行数:9,代码来源:connectionmanager.py
示例18: clientConnectionFailed
def clientConnectionFailed(self, connector, reason):
logger.info('connection failed: %s', reason.getErrorMessage())
ClientFactory.clientConnectionFailed(self, connector, reason)
if self.reconnect:
time.sleep(self.reconnect_delay)
connector.connect()
elif not self.protocols:
if self.onFinish:
self.onFinish.callback(None)
开发者ID:harnettlab,项目名称:sllurp,代码行数:9,代码来源:llrp.py
示例19: clientConnectionLost
def clientConnectionLost(self, connector, reason):
logger.info('lost connection: {}'.format(reason.getErrorMessage()))
ClientFactory.clientConnectionLost(self, connector, reason)
if self.reconnect:
time.sleep(self.reconnect_delay)
connector.connect()
elif not self.protocols:
if self.onFinish:
self.onFinish.callback(None)
开发者ID:ewfuentes,项目名称:sllurp,代码行数:9,代码来源:llrp.py
示例20: test_doStop
def test_doStop(self):
"""
L{_WrappingFactory.doStop} passes through to the wrapped factory's
C{doStop} method, allowing application-specific cleanup and logging.
"""
factory = ClientFactory()
factory.numPorts = 3
wf = endpoints._WrappingFactory(factory)
wf.doStop()
self.assertEqual(2, factory.numPorts)
开发者ID:AmirKhooj,项目名称:VTK,代码行数:10,代码来源:test_endpointspy3.py
注:本文中的twisted.internet.protocol.ClientFactory类示例由纯净天空整理自Github/MSDocs等源码及文档管理平台,相关代码片段筛选自各路编程大神贡献的开源项目,源码版权归原作者所有,传播和使用请参考对应项目的License;未经允许,请勿转载。 |
请发表评论