【发布时间】:2012-04-28 08:17:49
【问题描述】:
我正在尝试在 Twisted 中编写一个简单的 Echo 客户端,它将键盘输入发送到服务器,并由用户自己输入“q”终止。简而言之,我只是想修改this page 上的简单回显客户端(和变体)。一点也不性感,只有基本款。
我正在为非常基本的事件循环而苦苦挣扎。看起来我无法启动/停止循环内的反应器,因为停止的反应器不能是restarted。如果我不停止反应器,那么我将永远无法进入下一行获得键盘输入。
如果能帮助我的 echo 客户端正常工作,我们将不胜感激。
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()
【问题讨论】:
-
这不是真正的重复,jbreicis提供的答案比那边提供的答案要好得多。
-
我的回答对于具体任务来说并不好。通过我的回答,我试图更多地说明如何使遗留阻塞代码与 twisted 兼容。但是 - deferToThread 是最简单和最丑陋的方式。通常,您应该能够找到“本机”扭曲的替代品。至于线路输入,在扭曲示例部分twistedmatrix.com/trac/browser/trunk/doc/core/examples/stdin.py 中提供了更好的扭曲原生方法
-
您的答案更好,因为它包含信息,不像其他问题中的答案仅链接到不再存在的页面。随意不同意,但无论如何我发现你的帖子很有帮助:)
-
这里的答案是好是坏,问题还是重复。
标签: python twisted twisted.client