[Twisted-Python] How can a tcp client connect with multi servers?
Andrew Bennetts
andrew-twisted at puzzling.org
Thu Dec 1 20:57:51 MST 2005
On Fri, Dec 02, 2005 at 11:42:49AM +0800, Xu Ryan wrote:
> Would you like show me an simple example about this? I wrote one, but
> it dosn't work.
Sure. Thanks for taking the time to write a simple demonstration of your
problem, it makes it much easier to understand and discuss!
> __sender = None
>
> class p(Protocol):
> def connectionMade(self):
> print "Connecttion make"
>
> def sendMessage(self):
> self.transport.write("some message")
>
> def connectionLost(self, reason):
> print "Lost, reason", reason
>
> def sendCmd(addr, port, cmd, task, options = ""):
> """Send Cmd to
> """
> global __sender
>
> __sender.connectTCP(addr, port).addCallback(send,\
> cmd, task, options)
>
> def send(p,cmd, task, options):
> print "send"
> p.sendMessage()
> return p
>
> def finishConnection(p):
> print "lostConnection"
> p.transport.loseConnection()
>
> def initSendCommand():
> global __sender
> if not __sender:
> __sender = ClientCreator(reactor, p)
This all looks ok (except for the unused 'finishConnection' function).
> if __name__ == "__main__":
> def testSendMessage():
> time.sleep(2)
> sendCmd("localhost", 8009, "test send")
>
> initSendCommand()
> thread.start_new_thread(testSendMessage, ())
> reactor.run()
This is the problem. There's two issues here.
The first is that in general, a thread CANNOT call any Twisted functions
aside from reactor.callFromThread. Twisted is not thread safe. See
http://twistedmatrix.com/projects/core/documentation/howto/threading.html
The second, and more fundamental, is that threads are totally unnecessary for
this.
You can write that code block as:
if __name__ == "__main__":
initSendCommand()
reactor.callLater(2, sendCmd, "localhost", 8009, "test send")
reactor.run()
-Andrew.
More information about the Twisted-Python
mailing list