我是Twisted python的新手(Twisted 12.x,python 2.6.x,不幸的是我必须使用旧版本),我正在运行客户端/服务器,其中服务器回应来自客户端的简单消息(例如来自Twisted O&#re; reilly book的第2章)我在一个终端中运行服务器,然后在一个单独的终端中运行客户端。但客户端和服务器卡住了(没有返回)。什么失败了?
服务器:
from twisted.internet import protocol, reactor
class Echo(protocol.Protocol):
def dataReceived(self, data):
self.transport.write(data)
class EchoFactory(protocol.Factory):
def buildProtocol(self, addr):
return Echo()
reactor.listenTCP(50000, EchoFactory())
reactor.run()
客户:
from twisted.internet import reactor, protocol
class EchoClient(protocol.Protocol):
def connectionMade(self):
self.transport.write("Hello, world!")
def dataReceived(self, data):
print "Server said:", data
self.transport.loseConnection()
class EchoFactory(protocol.ClientFactory):
def buildProtocol(self, addr):
return EchoClient()
def clientConnectionFailed(self, connector, reason):
print "Connection failed."
reactor.stop()
def clientConnectionLost(self, connector, reason):
print "Connection lost."
reactor.stop()
reactor.connectTCP("localhost", 50000, EchoFactory())
reactor.run()
答案 0 :(得分:0)
您的dataReceived
,clientConnectionFailed
和clientConnectionLost
方法没有缩进,这意味着它们只是永远不会被调用的自由函数,而不是覆盖Protocol
上的方法或ClientFactory
。因此,您的客户端代码将获得默认的dataReceived
实现,即“什么都不做”。
另外,顺便说一句,Python 2.6不受安全支持,也不会收到更新。请至少升级到2.7.9版。您还应该升级到Twisted的最新版本,特别是如果这是针对新代码的话。没有正当理由使用这么久的软件;这样做是危险和不负责任的。