如果我的理解是正确的,文档中的这个示例只能写一次“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()
我有一些问题:
收到数据报时写“hello”的好方法是什么?在datagramReceived()
中调用startProtocol()
?
假设在收到数据报后要写入另一条消息,例如“有人在家吗?”。是否应该实现一个 AnyoneHome(DatagramProtocol)
类?但它应该如何“链接”到 Helloer
并连接到 react 器呢?
谢谢
已解决。看起来我可以在 datagramReceived()
中调用 self.transport.write()
。
我是一名优秀的程序员,十分优秀!