使用python中的twisted发送异步模式数据

时间:2015-02-19 13:09:41

标签: python networking twisted

我希望以异步模式(每当我在控制台中键入内容)将数据发送到服务器时,不仅如下面的代码那样。扭曲库中是否有可以处理此问题的协议功能?在下面找到仅发送建立连接的消息的代码。另一方面,我可以通过函数dataReceived以异步模式接收数据。是否有任何函数允许我以异步模式发送消息,因为dataReceived用于接收。

from twisted.internet import reactor, protocol


class QuoteProtocol(protocol.Protocol):
    def __init__(self, factory):
        self.factory = factory
    def connectionMade(self):
        self.sendQuote()
    def sendQuote(self):
        self.message(self.factory.quote)
    def dataReceived(self, data):
        print "Received quote:", data
        #self.transport.loseConnection()

class QuoteClientFactory(protocol.ClientFactory):
    def __init__(self, quote):
        self.quote = quote
    def buildProtocol(self, addr):
        return QuoteProtocol(self)
    def clientConnectionFailed(self, connector, reason):
        print 'connection failed:', reason.getErrorMessage()
        reactor.stop()
    def clientConnectionLost(self, connector, reason):
        print 'connection lost:', reason.getErrorMessage()
        reactor.stop()

message = "hello world"
reactor.connectTCP('127.0.0.1', 5000, QuoteClientFactory())
reactor.run()

1 个答案:

答案 0 :(得分:1)

如果您想异步处理来自终端的击键,可以查看TerminalProtocolhttp://twistedmatrix.com/documents/9.0.0/api/twisted.conch.insults.insults.TerminalProtocol.html