Python扭曲的客户端连接丢失 [英] Python Twisted Client Connection Lost

查看:112
本文介绍了Python扭曲的客户端连接丢失的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有这个扭曲的客户端,它与具有索引的扭曲服务器连接.我从命令行运行了此客户端.工作正常.现在,我对其进行了修改以使其可以循环运行(请参见main()),以便可以继续查询.但是客户端仅运行一次.下次仅显示connection lost \n Connection lost - goodbye!.

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

推荐答案

您不太了解Twisted反应堆的工作原理.

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

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

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

请参见 http://twistedmatrix.com/documents/10.2 .0/core/howto/reactor-basics.html 来获取与反应堆相关的各种主题.

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

这篇关于Python扭曲的客户端连接丢失的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆