ZeroMQ-Python
2024年3月28日大约 1 分鐘
這一節將使用 Python 及 ZeroMQ 來示範簡單的訊息傳遞,包括請求/回應(Request/Reply)以及發布/訂閱(Publish/Subscribe)模式的應用範例。
安裝 ZeroMQ for Python
在 Python 中使用 ZeroMQ 前,需要安裝 pyzmq 套件:
pip install pyzmq基本請求/回應模式
服務端程式碼(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")客戶端程式碼(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}")基本發布/訂閱模式
服務端程式碼(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)客戶端程式碼(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}")以上的程式碼範例展示了如何在 Python 環境中使用 ZeroMQ 進行基本的「請求/回應」和「發布/訂閱」通信模式。
練習 2
- 在 Python 中實際操作以上的範例程式。
 - 試著在不同電腦同時使用 Octave 及 Python 進行 ZeroMQ 之間的通訊。
 - 目前將連線擴充到至少三台電腦的連線,連線模式可自訂。
 
