user3240688
user3240688

Reputation: 1327

ZMQ connect and push - how to determine if it fails

I have a simple ZMQ program that establishes a zmq.PUSH socket, connects, and then tries to send messages.

import zmq

zcontext = zmq.Context()
zsock = zcontext.socket(zmq.PUSH)
zsock.connect("tcp://localhost:12345")

with open(sys.argv[1]) as f:
   for line in f:
       zsock.send(line)

This works fine when the other side is there. But if there's any problems with the listener on the other side (e.g. forgot to start listener, or I connected to wrong port), it just hangs after it tries to send about 1000 messages (depends on size of the default queue).

What's the right thing to do? If there's any issue with other side, I'd rather just print an error message and exit gracefully.

Upvotes: 2

Views: 3615

Answers (1)

Benyamin Jafari
Benyamin Jafari

Reputation: 33926

You can get zmq.error with the following snippet code:

import zmq
import time

zcontext = zmq.Context()
zsock = zcontext.socket(zmq.PUSH)
zsock.connect("tcp://localhost:12345")

try:
    with open(sys.argv[1]) as f:
        for line in f:
            zsock.send(line, flags=NOBLOCK)
            time.sleep(.1)

except zmq.ZMQError as exc:
    print(exc)

[NOTE]:

  • You can change the .connect() method with the .bind() in above code, and also change the other side bind to connect for a test case.

  • In .bind() method should be used 127.0.0.1 instead of localhost.


[UPDATE]:

  • With flags=NOBLOCK in .send() method, this raises ZMQError if the queue is full; otherwise, this waits until space is available. Thus, in this case, will be as the following:

    zsock.send(line, flags=NOBLOCK)

Upvotes: 1

Related Questions