写的不只是 "hello"

Writing more than just "hello"

如果我的理解是正确的,文档中的这个例子只能写"hello"一次:

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()

我有一些问题:

  1. 收到数据报时写"hello"有什么好方法?在 datagramReceived()?

  2. 中调用 startProtocol()
  3. 假设在收到数据报后要写入另一条消息,例如"anyone home?"。应该实施 class AnyoneHome(DatagramProtocol) 吗?但它应该如何"chained"到Helloer并连接到反应堆?

谢谢

已解决。看来我可以在 datagramReceived().

中调用 self.transport.write()