gpt4 book ai didi

python twisted - 发送的消息超时但没有得到响应

转载 作者:太空宇宙 更新时间:2023-11-03 14:34:00 25 4
gpt4 key购买 nike

我正在创建一种客户端-服务器实现,我想确保每条发送的消息都能得到响应。所以我想创建一个超时机制,它不检查消息本身是否已传递,而是检查传递的消息是否得到响应。

IE,对于两台计算机 1 和 2:

1: send successfully: "hello"
2: <<nothing>>
...
1: Didn't get a response for my "hello" --> timeout

我想通过为每条消息创建一个带有 id 的大 bool 数组来做到这一点,它将保存一个“进行中”标志,并将在收到消息的响应时设置。

我想知道是否有更好的方法。

谢谢,伊多。

最佳答案

有更好的方法,有趣的是我自己 just implemented here .它使用 TimeoutMixin实现您需要的超时行为,以及 DeferredLock将正确的回复与发送的内容相匹配。

from twisted.internet import defer
from twisted.protocols.policies import TimeoutMixin
from twisted.protocols.basic import LineOnlyReceiver

class PingPongProtocol(LineOnlyReceiver, TimeoutMixin):

def __init__(self):
self.lock = defer.DeferredLock()
self.deferred = None

def sendMessage(self, msg):
result = self.lock.run(self._doSend, msg)
return result

def _doSend(self, msg):
assert self.deferred is None, "Already waiting for reply!"

self.deferred = defer.Deferred()
self.deferred.addBoth(self._cleanup)
self.setTimeout(self.DEFAULT_TIMEOUT)
self.sendLine(msg)
return self.deferred

def _cleanup(self, res):
self.deferred = None
return res

def lineReceived(self, line):
if self.deferred:
self.setTimeout(None)
self.deferred.callback(line)
# If not, we've timed out or this is a spurious line

def timeoutConnection(self):
self.deferred.errback(
Timeout("Some informative message"))

我还没有测试过这个,它更像是一个起点。您可能需要在此处更改一些内容以满足您的目的:

  1. 我使用 LineOnlyReceiver — 这与问题本身无关,您需要将 sendLine/lineReceived 替换为适合您的协议(protocol)的 API 调用。

  2. 这是针对串行连接的,所以我不处理 connectionLost 等问题。您可能需要处理。

  3. 我喜欢直接在实例中保存状态。如果您需要额外的状态信息,请在 _doSend 中设置它并在 _cleanup 中清除它。有些人不喜欢这样 — 另一种方法是在 _doSend 中创建嵌套函数来关闭您需要的状态信息。不过,您仍然需要 self.deferred,否则 lineReceived(或 dataReceived)不知道该做什么。

如何使用

就像我说的,我为串行通信创建了这个,我不必担心工厂、connectTCP 等。如果您使用的是 TCP 通信,则需要弄清楚您需要的额外胶水。

# Create the protocol somehow. Maybe this actually happens in a factory,
# in which case, the factory could have wrapper methods for this.
protocol = PingPongProtocol()
def = protocol.sendMessage("Hi there!")
def.addCallbacks(gotHiResponse, noHiResponse)

关于python twisted - 发送的消息超时但没有得到响应,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/5139612/

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