单个请求的扭曲多个响应

时间:2015-11-19 10:38:06

标签: python twisted

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

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

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

修改

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

这适合我,但我想这不是正确的方法。因为我不知道它将如何将超过一个客户:)

1 个答案:

答案 0 :(得分:0)

这绝对不是正确的方法。除其他外,根据发生的情况,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并使你的服务器崩溃要好得多:)

相关问题