Python Twisted Client Connection Lost

99封情书 提交于 2019-12-23 15:17:13

问题


I have this twisted client, which connects with a twisted server having an index. I ran this client from command-line. It worked fine. Now I modified it to run in loop (see main()) so that I can keep querying. But the client runs only once. Next time it simply says connection lost \n Connection lost - goodbye!.

What am i doing wrong? In the loop I am reconnecting to the server, it that wrong?

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()

回答1:


You don't quite understand how the Twisted reactor works.

reactor.run() is starting up the reactor's event-loop --- it's a blocking call that loops "forever".

See http://twistedmatrix.com/documents/10.2.0/core/howto/reactor-basics.html for various reactor-related topics.



来源:https://stackoverflow.com/questions/4530845/python-twisted-client-connection-lost

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!