nibbana
nibbana

Reputation: 729

Send a message to a current thread or end it in ZeroMQ with Publish/Subscribe pattern

I am using ZeroMQ and a publish/subscribe pattern, in Python.

The server sends a message, as follows:

ZMQsocket_Publisher.send(subscription_string)

which is received by a client, that, as consequence, starts a loop, like this:

loop_condition = True
while loop_condition:
    ZMQsocket_Pusher.send(strings, zmq.SNDMORE)
    ZMQsocket_Pusher.send(data)

during which by default infinitely responds to the server in each iteration by sending back data to the server.

The question is: I would like to stop the while when a particular event occurs by either changing the condition or sending a break/interrupt signal. The problem I am facing right now is that if the while is still in progress, that particular client is not able to receive a "stop" message sent in a second moment by the server. Is there an easy way to stop the while or the execution when using this pattern?

Thank you in advance!

Upvotes: 0

Views: 184

Answers (1)

pavel_form
pavel_form

Reputation: 1790

As I understood, you have something like this:

subscription_string = your_client_receiver_socket.recv()
strings, data = some_processing(subscription_string)
loop_condition = True
while loop_condition:
    ZMQsocket_Pusher.send(strings, zmq.SNDMORE)
    ZMQsocket_Pusher.send(data)

If that's the case, simply add check of stop signal in while loop:

while loop_condition:
    ZMQsocket_Pusher.send(strings, zmq.SNDMORE)
    ZMQsocket_Pusher.send(data)
    try:
        stop = your_client_receiver_socket.recv(flags=zmq.DONTWAIT)
        if check_on_stop(stop):
            break
    except zmq.error.Again:
        pass

zmq.DONTWAIT flag will say receiver to receive in non-blocking way, raising zmq.error.Again exception if it couldn't receive anything. With this you can send some stop signal from server to stop client's loop.

Upvotes: 1

Related Questions