开发者

Send from Twisted client to Twisted server, only this one way

I want to use Twisted to rebuild the communication part of an existing application. This application does send data from the client to the server, only this way round, the server does not send anything.

How do I accomplish this with the event-driven concept of Twiste开发者_StackOverflow中文版d? I currently use the connectionMade method of Protocol, but I don't think this is the right way.

class Send(Protocol):

    def connectionMade(self):
        while True:
            data = queue.get()
            self.transport.write(data + "\n")
            self.transport.doWrite()

I'm pretty sure, this is not the way to do that. ;-)

Addition: My problem is, I cannot imaging what event to use for this. I think the connectionMade event is not the right one, but I will never reach any other event than connectionLost in my case, because the server does not send anything to the client. Should I change this behavior?


No, that is definitely not the right way to do that. Never, ever call doWrite.

The problem here is that I bet queue.get() just blocks until there is some data. If possible, use a non-blocking means of message passing rather than threads. For example, have your thread just callFromThread to your Send protocol to do something.

But, assuming a blocking 'get' call, something like this might work :

from twisted.internet.protocol import Protocol
from twisted.internet.threads import deferToThread

class Send(Protocol):
    def connectionMade(self):
        self.qget()

    def qget(self, data=None):
        if data is not None:
            self.transport.write(data)
        deferToThread(queue.get).addCallback(self.qget)


Here is an another question which uses UDP / Multicast to talk between server and client

  • UDP client and server with Twisted Python

I would also suggest some additional reading and examples from the twisted documentation it self.

  • http://krondo.com/?page_id=1327
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜