【问题标题】:python twisted simple server clientpython 扭曲的简单服务器客户端
【发布时间】:2012-12-09 16:13:51
【问题描述】:

我正在尝试构建一个简单的“每日报价”服务器和客户端,该服务器和客户端是从扭曲的教程文档修改而来的。我希望从客户那里打印“当日报价”以证明沟通。但是,据我所知,客户端没有连接。这是我的代码。

服务器

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

客户

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

【问题讨论】:

    标签: python networking network-programming twisted


    【解决方案1】:
    • 将 SimpleClientFactory 的实例,而不是类本身传递给 point.connect()
    • 如果您使用lineReceived,则从 twisted.protocol.basic.LineReceiver 子类 SimpleClient 而不是 Protocol
    • endpoint.listenpoint.connect的结果调用addErrback来处理错误

    【讨论】:

    • 它是 LineReceiver 的子类,使其工作。谢谢!
    猜你喜欢
    • 2012-09-27
    • 1970-01-01
    • 2011-05-30
    • 1970-01-01
    • 1970-01-01
    • 2011-03-15
    • 2012-06-04
    • 2023-03-23
    相关资源
    最近更新 更多