我正在学习网络编程与o'REilys Twisted网络编程必不可少的指南。 (使用pycharm IDE)
我有两个问题,函数maybeStopReactor()在pycharm中没有被识别,而QuoteClientFactory也不被视为一个已定义的类。
我该如何为此寻找解决方案?
class QuoteClientFactory(protocol.ClientFactory):
def __init__(self, quote):
self.quote = quote
def buildProtocol(self, addr):
return QuoteProtocol(self)
def clientConnectionFailed(self, connector, reason):
print("connecton failed:"), reason.getErrorMessage()
**maybeStopReactor()**
def clientConnectionLost(self, connector, reason):
print("connection lost"), reason.getErrorMessage()
maybeStopReactor()
def maybeStopReactor(self):
global quote_counter
quote_counter -=1
if not quote_counter:
reactor.stop()
quotes = [
"you snooze you lose",
"The early bird gets the worm",
"carpe diem"
]
quote_counter = len(quotes)
for quote in quotes:
**reactor.connectTCP('localhost', 6942, QuoteClientFactory(quote))**
reactor.run()
你的缩进是错的。这有点难以看清,因为代码跨越了分页符。你想要的是:
class QuoteClientFactory(protocol.ClientFactory):
def __init__(self, quote):
self.quote = quote
def buildProtocol(self, addr):
return QuoteProtocol(self)
def clientConnectionFailed(self, connector, reason):
print("connecton failed:"), reason.getErrorMessage()
maybeStopReactor()
def clientConnectionLost(self, connector, reason):
print("connection lost"), reason.getErrorMessage()
maybeStopReactor()
def maybeStopReactor():
global quote_counter
quote_counter -=1
if not quote_counter:
reactor.stop()
quotes = [
"you snooze you lose",
"The early bird gets the worm",
"carpe diem"
]
quote_counter = len(quotes)
for quote in quotes:
reactor.connectTCP('localhost', 6942, QuoteClientFactory(quote))
reactor.run()