问题
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