ZMQ socket connect timeout

天涯浪子 提交于 2019-12-24 21:36:23

问题


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

回答1:


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.

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).

Also see my reply to similar question.




回答2:


The problem is not the connection, but the DNS lookup. The blocking is done at the OS level, on the gethostbyname call.

Since the timeout is controlled by the OS, working around it is hard (but feasible). My suggestion is that you simply hardcode the IP



来源:https://stackoverflow.com/questions/21169031/zmq-socket-connect-timeout

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!