ZeroMQ and multiple subscribe filters in Python

Marc picture Marc · Dec 16, 2012 · Viewed 11.4k times · Source

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?

Answer

minrk picture minrk · Dec 16, 2012

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.