[Twisted-Python] Simple bidirectional Socket Client
marco.giusti at gmail.com
Fri Jun 14 06:31:46 MDT 2013
On Fri, Jun 14, 2013 at 02:11:20PM +0200, Raketenschnitzel wrote:
> class Communicator(ClientFactory):
> protocol = ControllerProtocol
> def __init__(self, Host, Port):
> if isinstance(Host, str) and isinstance(Port, int) :
> self.myHost = Host
> self.myPort = Port
> self.isConnected = False
> print 'Going To connect'
> def connectToMotherShip(self):
> reactor.connectTCP(self.myHost, self.myPort, self)
> class Operator:
> def __init__(self):
> self.myCommunicator = Communicator("192.168.1.12", 815)
> do other stuff ...
> I want an Operator Object that builds the Communicator. The
> communicator updates values of the Operator asynchronously if it
> receives messages. Each 10 secs the Operator will initiate a
> Communicator.sendMessage to send a status information to the server.
> Two questions:
> 1) Is it possible to solve my task like this with twisted and if so,
> how do I get my Communicator to not block my Operator?
The operator is blocked because reactor.run() is a loop, do not call it
inside the factory constructor.
isConnected = False
# do other stuff but do not use self.myCommunicator yet
factory = Communicator()
operator = Operator()
operator.myCommunicator = factory
reactor.connectTCP(host, port, factory)
> 2) If twisted is not the easiest way for this approach, do i have
> alternatives? I want at least something event driven. I also read
> about the asyncore packages, but people often recommend twisted over
> I simply want to send and receive message with a "threaded"
> communicator class, while doing other stuff in my Operator.
The great advantage of twisted is that you do not need to use threads to
communicate to the external world, use it only if you have to run code
that could "block" the main loop. But in my modest opinion, twisted is
the easiest way to do network programming.
More information about the Twisted-Python