9
votes

I am trying to use the ZeroMQ rep/req and cannot figure out how to handle server side errors. Look at the code from here:

socket.bind("tcp://*:%s" % port)
while True:
    #  Wait for next request from client
    message = socket.recv()
    print "Received request: ", message
    time.sleep (1)  
    socket.send("World from %s" % port)

My problem is what happens if the client calls socket.send() and then hangs or crashes. Wouldn't the server just get stuck on socket.send() or socket.recv() forever?

Note that it is not a problem with TCP sockets. With TCP sockets I can simply break the connection. With ZMQ, the connections are implicitly managed for me and I don't know if it is possible to break a 'session' or 'connection' and start over.

3

3 Answers

6
votes

You can terminate ZMQ sockets much the same way you terminate TCP sockets.

socket.close()

If you need to wait on a message but only up for a finite amount of time you can pass a timeout flag to socket.recv(timeout=1024) and then handle the timeout error case the same way you would when a TCP socket timeouts or disconnects. If you need to manage several sockets all of which may be in an error state then the Poller class will let you accomplish this.

2
votes

The ZMQ Z-guide offers lots of good hints on how to structure your services to handle different scenarios.

I think chapter 4 can be of interest to you, especially the Lazy Pirate Pattern.

Check out the examples of Lazy Pirate Server and Lazy Pirate Client.

0
votes

In general,

  1. Make sure you setsockopt() on the socket such that send and recv will not block forever. (Temporary blocking – be it client or server – is OK, but infinite blocking is bad because your application cannot do anything else)
  2. In the event that any of the I/O got an error,
    • If you are the client, close() the current socket and re-create a new one to establish a new connection
    • If you are the server, there's nothing else to do, you simply are waiting for a new connection. You will want to explore the Poller class.