pythonsocketszeromq

ZeroMQ and multiple subscribe filters in Python


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?


Solution

  • This works:

    #!/usr/bin/env python3
    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.subscribe('a')
    sub.subscribe('b')
    
    time.sleep(1)
    
    for word in [ 'alpha', 'beta', 'gamma', 'apple', 'carrot', 'bagel']:
        pub.send_string(word)
    
    time.sleep(1)
    
    for i in range(4):
        print(sub.recv_string(zmq.NOBLOCK))
    

    gives output:

    alpha
    beta
    apple
    bagel
    

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