我正在閱讀一本名爲「Twisted Network Programming Essentials rev.2」的書,我有一個報價服務器示例的問題。我從書上抄的代碼,但是當我啓動服務器,然後客戶端我有在客戶端側終端的錯誤:一個TCP報價服務器和客戶端在扭曲的Python錯誤
Traceback (most recent call last):
File "quoteclient.py", line 45, in <module>
reactor.connectTCP("triptrck.com", 8000, QuoteClientFactory())
TypeError: __init__() takes exactly 2 arguments (1 given)
這裏是爲quoteclient.py代碼:
from twisted.internet import protocol, reactor
class QuoteProtocol(protocol.Protocol):
def __init__(self, factory):
self.factory = factory
def connectionMade(self):
self.sendQuote()
def sendQuote(self):
self.transport.write(self.factory.quote)
def dataReceived(self, data):
print "Received quote:", data
self.transport.loseConnection()
class QuoteClientFactory(protocol.ClientFactory):
def __init__(self, quote):
self.quote = quote
def buildProtocol(self, addr):
return QuoteProtocol(self)
def clientConnectionFailed(self, connector, reason):
print "connection 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("triptrck.com", 8000, QuoteClientFactory())
reactor.run()
我明白,這個問題是我不傳遞「工廠」參數中的「QuoteProtocol」裏面調用「buildProtocol'功能'QuoteClientFactory'類。但我不知道我應該通過那裏。此外,我想通了,「QuoteClientFactory」在底部通話還需要第二個參數「報價」,所以我試圖把它這樣:
for quote in quotes:
reactor.connectTCP("triptrck.com", 8000, QuoteClientFactory(quote))
reactor.run()
結果是出乎意料的,對於我。該錯誤在客戶端側終端消失了,而不是我有這:
connection lost: Connection was closed cleanly.
connection lost: Connection was closed cleanly.
connection lost: Connection was closed cleanly.
可能有人給我解釋一下這是怎麼回事?爲什麼我們需要一個「初始化」與「工廠」和「報價」和我應該通過在那裏呢?
PS: 我也有在這本書中第一個例子中的一個問題,回聲工廠服務器,由於某種原因,數據不會經歷,我已經不得不改變「transport.write'至'sendLine'使用'LineReceiver'而不是'protocol.Protocol'。也許它也必須這樣做?