gpt4 book ai didi

Python Twisted 客户端连接丢失

转载 作者:太空宇宙 更新时间:2023-11-03 11:10:39 25 4
gpt4 key购买 nike

我有这个扭曲的客户端,它连接到一个有索引的扭曲服务器。我从命令行运行这个客户端。它运作良好。现在我将其修改为循环运行(参见 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()

最佳答案

您不太了解 Twisted react 器的工作原理。

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

参见 http://twistedmatrix.com/documents/10.2.0/core/howto/reactor-basics.html用于各种与 react 器相关的主题。

关于Python Twisted 客户端连接丢失,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/4530845/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com