I'm going through a book called "Twisted Network Programming Essentials rev.2" and I have a problem with example of quote server. I've copied the code from the book but when I launch server and then client I'm having an error in client-side terminal:
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)
Here's the code for the 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()
I do understand that the problem is I'm not passing a 'factory' parameter in the 'QuoteProtocol' call inside 'buildProtocol' function of 'QuoteClientFactory' class. But I have no clue what should I pass in there. Also i figured out that 'QuoteClientFactory' call in the bottom also would need a second parameter 'quote', so I've tried to put it like that:
for quote in quotes:
reactor.connectTCP("triptrck.com", 8000, QuoteClientFactory(quote))
reactor.run()
The result was unexpected, for me. The error in client-side terminal disappeared, instead I've got this:
connection lost: Connection was closed cleanly.
connection lost: Connection was closed cleanly.
connection lost: Connection was closed cleanly.
Could anybody explain me what's going on? Why do we need that 'init' with 'factory' and 'quote' and what should i pass in there?
P.S.: I've also had a problem in first example in the book, the echo factory server, where for some reason data wouldn't go through and I've had to change 'transport.write' to 'sendLine' using 'LineReceiver' instead of 'protocol.Protocol'. Maybe it has to do something with that too?