我正在尝试在Twisted中编写一个简单的Echo客户端,它将键盘输入发送到服务器,并由用户自己输入“q”终止。简而言之,我只是想修改this page上找到的简单回声客户端(和变体)。没什么性感,只是基础。
我正在努力解决非常基本的事件循环。看起来我无法在循环内启动/停止反应堆,因为停止的反应堆不能restarted。如果我不停止反应堆,那么我将永远不会到达获得键盘输入的下一行。
非常感谢帮助我的回音客户端工作的任何帮助。
from twisted.internet.protocol import ClientFactory
from twisted.protocols.basic import LineReceiver
from twisted.internet import reactor
class EchoClient(LineReceiver):
end="Bye-bye!"
def connectionMade(self):
#only write and end transmission if the message isn't empty
if len(self.factory.message) > 0:
self.sendLine(self.factory.message)
self.sendLine(self.end)
else:
#Else just terminate the connection
self.transport.loseConnection()
def lineReceived(self, line):
print "receive:", line
if line==self.end:
self.transport.loseConnection()
class EchoClientFactory(ClientFactory):
message = ""
def buildProtocol(self, address):
p = EchoClient()
p.factory = self
return p
def clientConnectionFailed(self, connector, reason):
reactor.stop()
def clientConnectionLost(self, connector, reason):
reactor.stop()
def main():
s = raw_input('Text to send (''q'' to terminate): ')
while s != 'q':
factory = EchoClientFactory()
factory.message = s
reactor.connectTCP('localhost', 8000, factory)
#This is bad because reactor cannot be restarted once it's been stopped
reactor.run()
s = raw_input('Text to send(''q'' to terminate): ')
if __name__ == '__main__':
main()
答案 0 :(得分:3)
作为一个经验法则 - 在非常罕见的情况下,您需要重新启动或停止reactor,除非您要终止程序alltogeather。如果您遇到一段会导致阻塞的代码,例如数据库访问,长时间计算或在你的情况下raw_input,你必须:找到一个扭曲的替代品(在数据库的情况下twisted.enterprise.adabi)或使其扭曲兼容。 “解块”代码的最简单方法是使用twisted.internet.threads中的deferToThread将阻塞位移动到线程中。 考虑这个例子:
from twisted.internet.threads import deferToThread as __deferToThread
from twisted.internet import reactor
def mmprint(s):
print(s)
class TwistedRAWInput(object):
def start(self,callable,terminator):
self.callable=callable
self.terminator=terminator
self.startReceiving()
def startReceiving(self,s=''):
if s!=self.terminator:
self.callable(s)
__deferToThread(raw_input,':').addCallback(self.startReceiving)
tri = TwistedRAWInput()
reactor.callWhenRunning(tri.start,mmprint,'q')
reactor.run()
你永远不必停止反应堆,因为raw_input会在外部线程中发生,每个新行都会延迟回调。