1 | initial version |
To use ZeroMQ with Python to publish and subscribe to multiple recipients, follow these steps:
Install zmq and pyzmq packages: Use the below command to install the zmq and pyzmq packages using pip.
pip install zmq
pip install pyzmq
Create a publisher and a subscriber: For this, import the zmq library and create two sockets with the help of the Context() function. The first socket represents the publisher that sends messages to multiple subscribers. The second socket represents the subscriber that receives messages from the publisher.
import zmq
context = zmq.Context()
publisher = context.socket(zmq.PUB)
publisher.bind("tcp://*:5555")
subscriber = context.socket(zmq.SUB)
subscriber.connect("tcp://localhost:5555")
subscriber.setsockopt(zmq.SUBSCRIBE, b'')
Define the messages to be published: You can define the messages to be published using a loop or by setting a fixed value.
# Using a loop
while True:
message = "Hello from Publisher"
publisher.send_string(message)
# Using a fixed value
message = "Hello from Publisher"
publisher.send_string(message)
Subscribe to the messages: To receive the messages published by the publisher, the subscriber needs to subscribe to the publisher.
while True:
message = subscriber.recv()
print("Received message: %s" % message)
Run the publisher and subscriber code: Once you have set up the publisher and subscriber, run both the codes in separate terminals. The subscriber code will receive the messages published by the publisher.
Note: You can modify the IP address and port number in the code according to your requirements.