2014-04-27 35 views
0

在TCP客戶端的例子:在Twisted中訪問協議傳輸的正確方法是什麼?

from twisted.internet import reactor, protocol 


# a client protocol 

class EchoClient(protocol.Protocol): 
    """Once connected, send a message, then print the result.""" 

    def connectionMade(self): 
     self.transport.write("hello, world!") 

    def dataReceived(self, data): 
     "As soon as any data is received, write it back." 
     print "Server said:", data 
     self.transport.loseConnection() 

    def connectionLost(self, reason): 
     print "connection lost" 

class EchoFactory(protocol.ClientFactory): 
    protocol = EchoClient 

    def clientConnectionFailed(self, connector, reason): 
     print "Connection failed - goodbye!" 
     reactor.stop() 

    def clientConnectionLost(self, connector, reason): 
     print "Connection lost - goodbye!" 
     reactor.stop() 


# this connects the protocol to a server runing on port 8000 
def main(): 
    f = EchoFactory() 
    reactor.connectTCP("localhost", 8000, f) 
    reactor.run() 

# this only runs if the module was *not* imported 
if __name__ == '__main__': 
    main() 

我有需要將數據發送到服務器的週期性任務。該任務的所有邏輯都在協議和工廠之外。是否通過f並使用f.protocol.transport.write("Something?")

回答

0

我也是扭曲的世界的新人,所以帶上一粒鹽,但我說它是可以接受的形式。

看到下面所以我舉了一個如何鉤住部分扭曲在一起的例子:Persistent connections in twisted。 (因爲它發生約週期性任務這個問題的答案的話真是太...)

編輯

哎呀,等待。你在那裏有一家工廠。

工廠在每次有連接時都會創建協議的新實例,因此您的f.protocol.transport.write將不起作用(將指向類,而不是該類的已連接實例)。嘗試從Persistent connections問題上運行我的代碼示例中,我做一個連接列表(self.clients在工廠),使用結構,你可以通過連接列表迭代使用的各種連接的.write

2

你可以調整你的代碼並利用一些新穎的API來避免在工廠做額外的工作來實現您的目標。 Mike Lutz的回答非常正確,我曾經在終結點之前向人們提出建議。現在我們有了端點,我建議人們使用這些端點。

端點的API讓你寫一個主要功能,看起來更像是這樣的:

def main(): 
    e = HostnameEndpoint(reactor, "localhost", 8000) 
    f = EchoFactory() 
    d = e.connect(f) 
    d.addCallback(connected) 
    return d 

def connected(protocol): 
    # protocol is an instance of EchoClient and is connected 
    return LoopingCall(doStuff, protocol).start(3) 

您也可以考慮將這個使用twisted.internet.task.react將採取的一些對你的反應器簿記照顧。

相關問題