Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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?

like image 572
Marc Avatar asked Dec 16 '12 19:12

Marc


People also ask

How does ZeroMQ support pub/sub?

ZeroMQ comes with support for Pub/Sub by way of four socket types: ZeroMQ uses multipart messages to convey topic information. Topics are expressed as an array of bytes, though you may use a string and with suitable text encoding. A publisher must include the topic in the message’s’ first frame, prior to the message payload.

What is a ZMQ subscriber?

The subscribers usually sets a filter on these topics for topic of their interests. Subscribers are created with ZMQ.SUB socket types. You should notice that a zmq subscriber can connect to many publishers.

What is the publish-subscribe pattern in ZeroMQ?

The publish-subscribe pattern is used for one-to-many distribution of data from a single publisher to multiple subscribers in a fan out fashion. The publish-subscribe pattern is formally defined by RFC 29/PUBSUB. ZeroMQ comes with support for Pub/Sub by way of four socket types: ZeroMQ uses multipart messages to convey topic information.

How to install ZeroMQ in Python?

First, to install ZeroMQ in python, use conda install pyzmq or pip install pyzmq depending on which python package manager you use. import zmq import time ctx = zmq.Context () sock = ctx.socket (zmq.PUB) sock.bind ( "tcp://*:1234" ) print ( "Starting loop..." ) i = 1 while True : msg = "Hi for the %d:th time..."


1 Answers

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.

like image 119
minrk Avatar answered Oct 10 '22 04:10

minrk