22

I'd like to subscribe to multiple filters with ZeroMQ in Python, using one socket.

sock.setsockopt(zmq.SUBSCRIBE, 'first.filter')
sock.setsockopt(zmq.SUBSCRIBE, 'second.filter')

But this doesn't work. Only the first one is taken in account. However, I read this on zeromq site:

Multiple filters may be attached to a single ZMQ_SUB socket, in which case a message shall be accepted if it matches at least one filter.

I'm using zmq 2.2.0.1. So, I wonder how to do that. Any ideas?

Rodrigo de Azevedo
  • 1,097
  • 9
  • 17
Marc
  • 1,340
  • 2
  • 14
  • 23

1 Answers1

35

This works:

import time
import zmq

ctx = zmq.Context()
pub = ctx.socket(zmq.PUB)
sub = ctx.socket(zmq.SUB)

url = "tcp://127.0.0.1:5555"
pub.bind(url)
sub.connect(url)

# subscribe to 'a' and 'b'
sub.setsockopt(zmq.SUBSCRIBE, b'a')
sub.setsockopt(zmq.SUBSCRIBE, b'b')

time.sleep(1)

for word in [ 'alpha', 'beta', 'gamma', 'apple', 'carrot', 'bagel']:
    pub.send(word)

time.sleep(1)

for i in range(4):
    print sub.recv(zmq.NOBLOCK)

gives output:

alpha
beta
apple
bagel

So both subscriptions do work. What's your exact code? Because maybe it's another issue.

minrk
  • 37,545
  • 9
  • 92
  • 87
  • Hi, thanks for your answer. Indeed this works, in my case I'm using a forwarder device between publisher and subscriber. Disabling it makes things work... still investigating why forwarder device prevents from having multiple filters... – Marc Dec 17 '12 at 17:48
  • Ok I reply to myself my code is a little bit complicated and I messed up somewhere. Works perfectly now, thanks! – Marc Dec 17 '12 at 18:32
  • What if you wanted to know which if the filters was caught when receiving. For instance whether you received for topic a, or b ? I am using jeromq though – flexxxit Nov 29 '18 at 08:38
  • @Marc I have exactly the same problem. I also have an XPUB and XSUB between my Publisher and Subscriber. When I subscribe to multiple topics on the subscriber, I only get the messages for the first topic. How could you solve your problem? Did you just remove the proxy? – doome161 Mar 18 '22 at 12:48