2015-03-08 28 views
1

如果我的理解是正确的,这个例子中的文档只能写“你好”一次:写作不仅仅是“你好”

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”的好方法?致电startProtocol()datagramReceived()

  2. 假设在接收到数据报之后要写入另一条消息,例如“any home?”。应该实施类AnyoneHome(DatagramProtocol)?但是,它应该如何“链接”到Helloer并且连接到反应堆?

感谢

回答

1

解决。看起来我可以在datagramReceived()中拨打self.transport.write()

+0

是的,但我只能在2天后接受我自己的答案。 – Kar 2015-03-09 06:23:59

相关问题