2014-04-27 22 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将采取的一些对你的反应器簿记照顾。

相关问题