eat_a_lemon
eat_a_lemon

Reputation: 3208

python twisted simple server client

I am trying to build a simple "quote of the day" server and client modified from the twisted tutorial documentation. I want the "quote of the day" to be printed from the client to prove the communication. However, from what I can tell the client is not connecting. Here is my code.

Server

from twisted.python import log
from twisted.internet.protocol import Protocol
from twisted.internet.protocol import Factory
from twisted.internet.endpoints import TCP4ServerEndpoint
from twisted.internet import reactor

class QOTD(Protocol):
    def connectionMade(self):
        self.transport.write("An apple a day keeps the doctor away\r\n") 
        self.transport.loseConnection()

class QOTDFactory(Factory):
    def buildProtocol(self, addr):
        return QOTD()

# 8007 is the port you want to run under. Choose something >1024
endpoint = TCP4ServerEndpoint(reactor, 8007)
endpoint.listen(QOTDFactory())
reactor.run()

Client

import sys
from twisted.python import log
from twisted.internet import reactor
from twisted.internet.protocol import Factory, Protocol
from twisted.internet.endpoints import TCP4ClientEndpoint

class SimpleClient(Protocol):
    def connectionMade(self):
        log.msg("connection made")
        #self.transport.loseConnection()

    def lineReceived(self, line):
        print "receive:", line

class SimpleClientFactory(Factory):
    def buildProtocol(self, addr):
        return SimpleClient()

def startlog():
    log.startLogging(sys.stdout)

point =  TCP4ClientEndpoint(reactor, "localhost", 8007)
d = point.connect(SimpleClientFactory)
reactor.callLater(0.1, startlog)
reactor.run()

Upvotes: 0

Views: 720

Answers (1)

jfs
jfs

Reputation: 414235

  • pass instance of SimpleClientFactory, not the class itself to point.connect()
  • subclass SimpleClient from twisted.protocol.basic.LineReceiver instead of Protocol if you use lineReceived
  • call addErrback on the results of endpoint.listen and point.connect to handle errors

Upvotes: 2

Related Questions