質問

このツイストクライアントは、インデックスを持つツイストサーバーに接続しています。このクライアントをコマンドラインから実行しました。うまくいきました。今、私はそれを変更してループで実行しました(参照 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()
役に立ちましたか?

解決

ツイストリアクターがどのように機能するかはよくわかりません。

reactor.run() Reactorのイベントループを起動しています---これは「永遠に」ループするブロッキングコールです。

見る http://twistedmatrix.com/documents/10.2.0/core/howto/reactor-basics.html さまざまな原子炉関連のトピック用。

ライセンス: CC-BY-SA帰属
所属していません StackOverflow
scroll top