【问题标题】:Python Twisted Client Connection LostPython Twisted 客户端连接丢失
【发布时间】:2011-05-30 16:08:37
【问题描述】:

我有这个扭曲的客户端,它与一个具有索引的扭曲服务器连接。我从命令行运行了这个客户端。它工作得很好。现在我将其修改为循环运行(请参阅main()),以便我可以继续查询。但是客户端只运行一次。下次它只是说connection lost \n Connection lost - goodbye!

我做错了什么?在循环中我重新连接到服务器,是不是错了?

from twisted.internet import reactor
from twisted.internet import protocol

from settings import AS_SERVER_HOST, AS_SERVER_PORT

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

    def connectionMade(self):
        self.transport.write(self.factory.query)

    def dataReceived(self, data):
        "As soon as any data is received, write it back."
        if data == '!':
            self.factory.results = ''
        else:
            self.factory.results = data
        self.transport.loseConnection()

    def connectionLost(self, reason):
        print "\tconnection lost"

class Spell_Factory(protocol.ClientFactory):
    protocol = Spell_client

    def __init__(self, query):
        self.query   = query
        self.results = ''

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

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

# this connects the protocol to a server runing on port 8090
def main(): 
    print 'Connecting to %s:%d' % (AS_SERVER_HOST, AS_SERVER_PORT)
    while True:
        print
        query = raw_input("Query:")
        if query == '': return
        f = Spell_Factory(query) 
        reactor.connectTCP(AS_SERVER_HOST, AS_SERVER_PORT, f)
        reactor.run()
        print f.results
    return

if __name__ == '__main__':
    main()

【问题讨论】:

    标签: python twisted twisted.web twisted.client twisted.internet


    【解决方案1】:

    你不太了解 Twisted reactor 的工作原理。

    reactor.run() 正在启动反应器的事件循环 --- 这是一个“永远”循环的阻塞调用。

    请参阅http://twistedmatrix.com/documents/10.2.0/core/howto/reactor-basics.html 了解各种与反应器相关的主题。

    【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2015-08-17
    • 1970-01-01
    • 2011-12-27
    • 2019-02-20
    相关资源
    最近更新 更多