Search code examples
pythontwisted

Writing more than just "hello"


If my understanding is correct, this example in the docs could only write "hello" once:

from twisted.internet.protocol import DatagramProtocol
from twisted.internet import reactor

class Helloer(DatagramProtocol):

    def startProtocol(self):
        host = "192.168.1.1"
        port = 1234

        self.transport.connect(host, port)
        print "now we can only send to host %s port %d" % (host, port)
        self.transport.write("hello") # no need for address

    def datagramReceived(self, data, (host, port)):
        print "received %r from %s:%d" % (data, host, port)

    # Possibly invoked if there is no server listening on the
    # address to which we are sending.
    def connectionRefused(self):
        print "No one listening"

# 0 means any port, we don't care in this case
reactor.listenUDP(0, Helloer())
reactor.run()

I have some questions:

  1. What is a good way to write "hello" when a datagram is received? Call startProtocol() in datagramReceived()?

  2. Suppose another message is to be written, e.g., "anyone home?", after receiving a datagram. Should a class AnyoneHome(DatagramProtocol) be implemented? But how should it be "chained" to Helloer and be hooked up to the reactor?

Thanks


Solution

  • Solved. Looks like I could just call self.transport.write() in datagramReceived().