【问题标题】:Twisted multiple responses for single request单个请求的扭曲多个响应
【发布时间】:2016-02-21 10:53:47
【问题描述】:

我有一个 LineReceiver 协议,想发送两个这样的响应:

def handle_CLIENT(self, data):
    ...
    self.sendLine(r1.raw)
    ...
    self.sendLine(r2.raw)

Twisted 将两个响应合并为一个,例如 Multiple responses in Twisted。客户是专有的,我无法改变它的行为。使它起作用的正确方法是什么?谢谢。

编辑

def handle_CLIENT(self, data):
    ...
    self.sendLine(r1.raw)
    reactor.doIteration(0.5)
    ...
    self.sendLine(r2.raw)

这对我有用,但我想这不是正确的方法。因为我不知道何时会有多个客户:)

【问题讨论】:

    标签: python twisted


    【解决方案1】:

    这绝对不是正确的方法。除此之外,根据发生的情况,doIteration 可能会导致无限循环或崩溃。

    你想使用的是callLater,它可以让你在未来的某个时间运行一个函数。

    您尝试做的是强制将两个响应分成两个单独的 TCP 段,因为您的对等点有问题。有关原因的解释,请参阅this Twisted FAQ。请注意,这在一般情况下不起作用,并且您的专有客户端刚刚损坏

    但是,您可以通过这样做大部分时间让它工作:

    def handle_CLIENT(self, data):
        self.transport.pauseProducing()
        def sendFirstLine():
            self.sendLine(r1.raw)
        def sendSecondLine():
            self.sendLine(r2.raw)
            # now that we've sent the second line we can accept more requests; if
            # we accept requests in the middle, we might send responses interleaved
            # with each other, which will probably break your client
            self.transport.resumeProducing()
    
        reactor.callLater(0, sendFirstLine)
        reactor.callLater(0.5, sendSecondLine)
    

    同样,TCP 是一种字节流协议,即使有半秒的延迟,慢速网络可能会导致你的两个响应在你和你的中间的某个路由器上粘在一起客户。你不能依赖这个。但这可能足以让你摆脱当前的困境——而且这比调用doIteration 并让你的服务器崩溃要好得多:)

    【讨论】:

    • 非常感谢您的澄清!
    猜你喜欢
    • 2018-03-26
    • 1970-01-01
    • 1970-01-01
    • 2021-08-06
    • 2012-08-04
    • 1970-01-01
    • 2021-07-17
    • 2011-05-17
    • 1970-01-01
    相关资源
    最近更新 更多