跳至主要內容

ZeroMQ-Python

Jia-Yin大约 1 分钟coursecomm

这一节将使用 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

  1. 在 Python 中实际操作以上的范例程式。
  2. 试著在不同计算机同时使用 Octave 及 Python 进行 ZeroMQ 之间的通信。
  3. 目前将连线扩充到至少三台计算机的连线,连线模式可自订。