You have access to all the objects you want. factory is responsible for instantiating the protocol, so if you want to save the protocol instance where it can use the factory, override buildProtocol
and save the instance:
class MyFactory(ClientFactory): protocol = MyProtocol ... def buildProtocol(self, address): proto = ClientFactory.buildProtocol(self, address) self.connectedProtocol = proto return proto
However, this approach is missing from one important function. This does not make it easy to determine when buildProtocol
and connectedProtocol
called. If you try to use this attribute naively:
factory = MyFactory() reactor.connectTCP(host, port, factory) factory.connectedProtocol.send_message(...)
The code will not work with AttributeError
because the connection has not yet been configured. Since Twisted is an event, you must make sure to use this code in response to an event that says the connection has been set up.
You can do this by activating the callback when the protocol is built instead of just setting the attribute. Twisted really has a factory helper that already does something like this:
from twisted.internet.protocol import ClientCreator cc = ClientCreator(reactor, MyProtocol) whenConnected = cc.connectTCP(host, port)
You can also save the link to connectedProtocol
in the cbConnected
callback cbConnected
that you can continue to use it later. You can also start any other operations that you want to use the connected protocol in cbConnected
so that they do not try to use the connection before it is really available.
Jean-paul calderone
source share