ZeroMQ-Python
March 28, 2024Less than 1 minute
This section will use Python and ZeroMQ to demonstrate simple message passing, including examples of Request/Reply and Publish/Subscribe patterns.
Installing ZeroMQ for Python
Before using ZeroMQ in Python, you need to install the pyzmq
package:
pip install pyzmq
Basic Request/Reply Pattern
Server-side Code (Python)
import zmq
context = zmq.Context()
socket = context.socket(zmq.REP)
socket.bind("tcp://*:5555")
print("Waiting for clients ...")
while True:
received_data = socket.recv_string()
print(f"Received {received_data}")
socket.send_string("World")
Client-side Code (Python)
import zmq
context = zmq.Context()
socket = context.socket(zmq.REQ)
socket.connect("tcp://localhost:5555")
for request_nbr in range(1, 11):
print(f"Sending Hello {request_nbr}...")
socket.send_string("Hello")
received = socket.recv_string()
print(f"Received {request_nbr} = {received}")
Basic Publish/Subscribe Pattern
Server-side Code (Python)
import zmq
from random import randint
context = zmq.Context()
publisher = context.socket(zmq.PUB)
publisher.bind("tcp://*:5556")
while True:
dice_number = randint(1, 6)
data = f"Dice {dice_number}"
publisher.send_string(data)
score = randint(1, 100)
data = f"Score {score}"
publisher.send_string(data)
Client-side Code (Python)
import zmq
context = zmq.Context()
subscriber = context.socket(zmq.SUB)
subscriber.connect("tcp://localhost:5556")
msgfilter = "Dice"
subscriber.setsockopt_string(zmq.SUBSCRIBE, msgfilter)
total = 0
print("Receiving 100 dice numbers...")
for update_nbr in range(100):
string = subscriber.recv_string()
_, number = string.split()
print(f"{number}", end=" ")
total += int(number)
print(f"\n\nAverage = {total/100:.2f}")
The above code examples demonstrate how to use ZeroMQ in a Python environment for basic "Request/Reply" and "Publish/Subscribe" communication patterns.
Exercise 2
- Implement the example programs above in Python.
- Try communicating between different computers using Octave and Python with ZeroMQ simultaneously.
- Expand the connection to at least three computers with customizable connection modes.