2015-03-08 24 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

相關問題