【问题标题】:dataReceived() method confusing behaviour in python twisted frameworkpython扭曲框架中的dataReceived()方法令人困惑的行为
【发布时间】:2012-09-30 07:46:14
【问题描述】:

我正在尝试学习 python 扭曲的互联网框架,但有一件事让我感到困惑。使用 telnet 进行的初始测试表明,只要接收到数据,就会调用 protocol.Protocol.dataReceived() 方法。因此,如果我将其定义如下,它会在触发前等待 EOL:

def dataReceived(self, data):
    print "MyProtocol::dataReceived, (%s)" %(data)

输出:

MyProtocol::dataReceived, (dgdfg
)

但是,只要我添加了额外的一行:

def dataReceived(self, data):
    print "MyProtocol::dataReceived, (%s)" %(data)
    self.transport.write(data)

它会为每个角色触发。

输出:

MyProtocol::dataReceived, (d)
MyProtocol::dataReceived, (g)
MyProtocol::dataReceived, (d)
MyProtocol::dataReceived, (f)
MyProtocol::dataReceived, (g)
MyProtocol::dataReceived, (
)

对这里发生的事情有什么想法吗?

工厂是protocol.Factory,协议是protocol.Protocol

谢谢

【问题讨论】:

    标签: python twisted


    【解决方案1】:

    dataReceived 触发 (docs) 之前不会进行行缓冲,因此无法保证您收到的内容是 EOL 分隔的。不过,这不太可能是您问题的根源,因为您发送的消息适合默认的读取块大小。您能否分享您的其余代码?

    有一个 LineReceiver 协议,您可以查看 (docs) 为您处理行缓冲。这是一个例子:

    from twisted.internet import reactor
    from twisted.protocols import basic
    
    class EchoLine(basic.LineReceiver):
        delimiter = '\n'  # default is '\r\n'
    
        def lineReceived(self, line):
            print("received: %s" % line)
            self.sendLine(line)
    
    class EchoFactory(protocol.ServerFactory):
        protocol = EchoLine
    
    reactor.listenTCP(port, EchoFactory())
    reactor.run()
    

    【讨论】:

      【解决方案2】:

      您使用的客户端有时会在发送前进行行缓冲。也许您在两个客户端之间切换以获得缓冲行为的差异,或者您在客户端中切换了缓冲选项。

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2018-03-06
        • 1970-01-01
        • 2020-04-07
        • 2011-11-09
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多