0

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()
4

1 回答 1

2
  • 传递 SimpleClientFactory 的实例,而不是类本身point.connect()
  • 如果您使用,则从 twisted.protocol.basic.LineReceiver 子类 SimpleClient 而不是 ProtocollineReceived
  • 对结果调用 addErrbackendpoint.listenpoint.connect处理错误
于 2012-12-09T16:46:24.060 回答