ZeroMQ 本機程式測試
ZeroMQ
安裝 Python ZMQ 套件,安裝前必須先裝過 Cython 套件。
$sudo pip3 install pyzmq
接著測試以下範例程式。
範例程式
參考來源:http://blog.ez2learn.com/2011/12/31/transport-lib-of-new-era-zeromq/
將以上來源的範例程式測試並由 Python 2 轉成 Python 3,目標為分配 9 組隨機的加法計算式給客戶端運算,並回傳結果至伺服端。
客戶端(rep.py
):
import os import zmq context = zmq.Context() socket = context.socket(zmq.REP) socket.connect("tcp://localhost:7788") print('Worker {} is running ...'.format(os.getpid())) while True: # receive request a, b = socket.recv_multipart() a = int(a) b = int(b) print('Compute {} + {} and send response'.format(a, b)) socket.send_string(str(a + b))
伺服端(req.py
):
import zmq import random import time context = zmq.Context() socket = context.socket(zmq.REQ) socket.bind("tcp://*:7788") # wait all worker connected time.sleep(1) for i in range(9): a = random.randint(0, 100) b = random.randint(0, 100) print('Compute {} + {} ...'.format(a, b)) # send request to peer socket.send_multipart([str(a).encode("utf-8"), str(b).encode("utf-8")]) # receive response from peer rep = socket.recv().decode("utf-8") print(' = {}'.format(rep))
此時先啟動 4 組客戶端程式,接著再啟動伺服端程式。
可以發現,每個客戶端程式接收了 2 組計算式(第一個接收 3 組),完成 9 組加法計算。
Comments
comments powered by Disqus