views:

99

answers:

2

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 Twisted? 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?

+1  A: 

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

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

pyfunc
+1  A: 

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)
Glyph
http://stackoverflow.com/questions/1538617/http-download-very-big-file/1657324#1657324 talks about the dangers of loops in Twisted code, and also covers producers/consumers which might also be helpful to the questioner.
Jean-Paul Calderone
Yes, it sounds reasonable not to use loops nor blocking calls in Twisted events, this would make the event-driven framework senseless.
Manuel Faux