ZMQ 套接字连接超时 [英] ZMQ socket connect timeout

查看:43
本文介绍了ZMQ 套接字连接超时的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在尝试将套接字连接到端点,直到套接字从该端点接收数据.这是因为此时端点可能不存在.

I'm trying to connect a socket to an endpoint until the socket receives data from that endpoint. This is because the endpoint might not exist at that time.

目前连接停止,我猜是因为它无法解析主机名,这需要一段时间.

Currently the connect stalls, i'm guessing because it can't resolve the hostname and that takes a while.

有没有办法在套接字连接上设置超时?

Is there any way to set a timeout on a socket connect?

import zmq
import time

endpoint = 'tcp://doesnt_exist:12345'

ctx = zmq.Context.instance()
s = ctx.socket(zmq.SUB)

t = time.time()
try:
    s.connect(endpoint)
except Exception:
    pass

print time.time() - t

推荐答案

如果您为 connect 提供主机名,ZeroMQ 通过调用 getaddrinfo 使用同步 DNS 解析,这就是您看到 connect 调用阻塞的原因.

If you provide a host name to connect, ZeroMQ uses synchronous DNS resolution via a call to getaddrinfo, which is why you see the connect call blocking.

如果您确实需要以可控方式connect,我建议您自己进行 DNS 解析,使用 Python 已经可用的异步 DNS 解析器之一(检查 这个例子基于pyuc/pycares).

If you really need to connect in controllable way, I suggest you do DNS resolve on your own, using one of the asynchronous DNS resolvers already available for Python (check this example based on pyuc/pycares).

另见我对类似问题的回复.

这篇关于ZMQ 套接字连接超时的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆