【问题标题】:Twisted close web server connection扭曲关闭 Web 服务器连接
【发布时间】:2015-08-20 02:44:18
【问题描述】:

我正在使用twisted 编写一个简单的Web 服务器应用程序。应用程序将获取一个字符串并返回它接收到的字符串的反转。

一切正常。现在如果有 5 分钟不活动,我需要关闭套接字连接。

这是我的服务器代码:-

from twisted.internet import reactor, protocol


class Echo(protocol.Protocol):
    """This is just about the simplest possible protocol"""

    def dataReceived(self, data):
        "As soon as any data is received, write it back."
        self.transport.write(data[::-1])


def main():
    """This runs the protocol on port 8000"""
    factory = protocol.ServerFactory()
    factory.protocol = Echo
    reactor.listenTCP(8000,factory)
    reactor.run()

# this only runs if the module was *not* imported
if __name__ == '__main__':
    main()
~

【问题讨论】:

标签: python twisted


【解决方案1】:

将这些方法添加到您的类中:

def connectionMade(self):
    def terminate():
        self.terminateLater = None
        self.transport.abortConnection()
    self.terminateLater = reactor.callLater(60 * 5, terminate)

def connectionLost(self, reason):
    delayedCall = self.terminateLater
    self.terminateLater = None
    if delayedCall is not None:
        delayedCall.cancel()

这样当建立连接时,您的协议将在 5 分钟内安排一个定时调用来关闭连接。否则关闭连接,将取消超时。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2018-05-22
    • 1970-01-01
    • 2011-09-29
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2019-11-02
    • 1970-01-01
    相关资源
    最近更新 更多