客戶:雙絞協議實例變量?
#!/usr/bin/env python
from twisted.internet import reactor, protocol
class EchoClient(protocol.Protocol):
def __init__(self, arg):
self.arg = arg
def connectionMade(self):
self.transport.write("hello, world!")
def dataReceived(self, data):
print "Server said:", data
self.transport.loseConnection()
def connectionLost(self, reason):
print "connection lost"
class EchoFactory(protocol.ClientFactory):
protocol = EchoClient
def buildProtocol(self, address):
proto = protocol.ClientFactory.buildProtocol(self, address, 12)
self.connectedProtocol = proto
return proto
def clientConnectionFailed(self, connector, reason):
print "Connection failed - goodbye!"
reactor.stop()
def clientConnectionLost(self, connector, reason):
print "Connection lost - goodbye!"
reactor.stop()
def main():
f = EchoFactory()
reactor.connectTCP("localhost", 8000, f)
reactor.run()
if __name__ == '__main__':
main()
SERVER:
#!/usr/bin/env python
from twisted.internet import reactor, protocol
from twisted.application import service, internet
class Echo(protocol.Protocol):
def dataReceived(self, data):
self.transport.write(data)
def main():
factory = protocol.ServerFactory()
factory.protocol = Echo
reactor.listenTCP(8000,factory)
reactor.run()
if __name__ == '__main__':
main()
錯誤:
exceptions.TypeError: buildProtocol() takes exactly 2 arguments (3 given)
問題:
我怎樣才能在CLIENT
的EchoClient
類接受參數並給實例變量(例如在上面的構造函數EchoClient
中)?如下所述,先前建議我重寫buildProtocol
函數,但是我這樣做的嘗試已導致我出現上述錯誤。我不確定該從哪裏出發。我想我的問題可以概括爲:如何將實例變量添加到協議?
謝謝!這似乎工作得很好! – rarify
爲了記錄,這是一個很好的答案! :) – jathanism