[Twisted-Python] How can a tcp client connect with multi servers?
Xu Ryan
xuryans at gmail.com
Fri Dec 2 00:44:06 EST 2005
I use the thread to make the sendCmd be called after the reactor run.
Because in the real application, I should start the server(reactor)
first, and other logic will call the sendCmd, so I can't fix it before
reactor.run() (as callLater(foo)). What should I do ?
On 12/2/05, Andrew Bennetts <andrew-twisted at puzzling.org> wrote:
> 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.
>
>
> _______________________________________________
> Twisted-Python mailing list
> Twisted-Python at twistedmatrix.com
> http://twistedmatrix.com/cgi-bin/mailman/listinfo/twisted-python
>
--
Xu Ryans
More information about the Twisted-Python
mailing list