gpt4 book ai didi

如果 n 秒后没有读取,则 Twisted TCP 服务器超时

转载 作者:行者123 更新时间:2023-12-02 21:12:22 24 4
gpt4 key购买 nike

通过以下示例,如何最好地在读取时实现看门狗定时器?

如果没有收到任何数据,我希望服务器在 n 秒后关闭连接。然后客户端必须重新连接才能继续发送数据。

from twisted.internet import reactor, protocol as p
from threading import Lock

class Echo(p.Protocol):
def __init__(self, factory):
self.factory = factory

def connectionMade(self):
with self.factory.mutex:
self.factory.clients.append(self)

def connectionLost(self, reason):
print('Connection lost)
with self.factory.mutex:
self.factory.clients.remove(self)

def dataReceived(self, data):
self.transport.write(data)

class EchoFactory(p.Factory):
def __init__(self):
self.clients = []
self.mutex = Lock()


def buildProtocol(self, addr):
print 'Connection by', addr
return Echo(self)

reactor.listenTCP(5007, EchoFactory())
reactor.run()

最佳答案

Twisted 中有一个针对此模式的助手,twisted.protocols.policies.TimeoutMixin:

from twisted.protocols.policies import TimeoutMixin
from twisted.internet.protocol import Protocol

class YourProtocol(Protocol, TimeoutMixin):
def connectionMade(self):
self.setTimeout(N)

def dataReceived(self, data):
self.resetTimeout()

def timeoutConnection(self):
self.transport.abortConnection()

关于如果 n 秒后没有读取,则 Twisted TCP 服务器超时,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/22497919/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com