<p>这是个老问题。但是,希望它能帮助其他人。在</p>
<blockquote>
<p>The problem that I am having is getting hold of subsequent Protocol objects for the reconnections.</p>
</blockquote>
<p>提供可调用的<code>prepareConnection</code>构造函数。它将提供电流连接。在</p>
<p>在下面的示例中,<code>MyService</code>将自身附加到<code>MyFactory</code>。主要原因是<code>MyFactory</code>可以让<code>MyService</code>知道<code>ClientService</code>何时断开连接。这是可能的,因为<code>ClientService</code>在断开连接时调用<code>Factory.stopFactory</code>。在</p>
<p>下次<code>ClientService</code>重新连接时,它将调用其提供当前协议实例的<code>prepareConnection</code>。在</p>
<p>(重新连接)客户端服务:</p>
<pre><code># clientservice.py
# twistd -y clientservice.py
from twisted.application import service, internet
from twisted.internet.protocol import Factory
from twisted.internet import endpoints, reactor
from twisted.protocols import basic
from twisted.logger import Logger
class MyProtocol(basic.Int16StringReceiver):
_log = Logger()
def stringReceived(self, data):
self._log.info('Received data from {peer}, data={data}',
peer=self.transport.getPeer(),
data=data)
class MyFactory(Factory):
_log = Logger()
protocol = MyProtocol
def stopFactory(self):
# Let service know that its current connection is stale
self.service.on_connection_lost()
class MyService(internet.ClientService):
def __init__(self, endpoint, factory):
internet.ClientService.__init__(self,
endpoint,
factory,
prepareConnection=self.on_prepare_connection)
factory.service = self # Attach this service to factory
self.connection = None # Future protocol instance
def on_prepare_connection(self, connection):
self.connection = connection # Attach protocol to service
self._log.info('Connected to {peer}',
peer=self.connection.transport.getPeer())
self.send_message('Hello from prepare connection!')
def on_connection_lost(self):
if self.connection is None:
return
self._log.info('Disconnected from {peer}',
peer=self.connection.transport.getPeer())
self.connection = None
def send_message(self, message):
if self.connection is None:
raise Exception('Service is not available')
self.connection.sendString(bytes(message, 'utf-8'))
application = service.Application('MyApplication')
my_endpoint = endpoints.clientFromString(reactor, 'tcp:localhost:22222')
my_factory = MyFactory()
my_service = MyService(my_endpoint, my_factory)
my_service.setServiceParent(application)
</code></pre>
<p>根据twisted示例对echo服务器稍作修改:</p>
^{pr2}$