ZeroMQ只是一个库,要想在python中使用需要下载相应的模块python3-zmq,下面直接介绍它的3中基本的模式。
import zmq
import time
context = zmq.Context()
socket = context.socket(zmq.REP)
socket.bind("tcp://*:5555")
while True:
# Wait for next request from client
message = socket.recv()
print("Received request: ", message.decode('utf-8'))
time.sleep(1) # Do some 'work'
# Send reply back to client
socket.send_string("World")
client
import zmq
context = zmq.Context()
subscriber = context.socket(zmq.REQ)
subscriber.connect("tcp://localhost:5555")
for request in range(1, 10):
print("Sending request ", request, "...")
subscriber.send_string("Hello")
# Get the reply.
message = subscriber.recv()
print("Received reply ", request, "[", message.decode('utf-8'), "]")
server
# -*- coding=utf-8 -*-
import zmq
import time
context = zmq.Context()
socket = context.socket(zmq.PUB)
socket.bind("tcp://*:5555")
i = 1
while True:
print('发送消息')
socket.send_string("消息群发" + str(i))
time.sleep(1)
i += 1
client1
# -*- coding=utf-8 -*-
import zmq
context = zmq.Context()
socket = context.socket(zmq.SUB)
socket.connect("tcp://localhost:5555")
socket.setsockopt_string(zmq.SUBSCRIBE, '') # 消息过滤
while True:
response = socket.recv() # 消息发送是以bytes形式,接收后需要解码
print("response: %s" % response.decode('utf-8'))
client2
# -*- coding=utf-8 -*-
import zmq
context = zmq.Context()
socket = context.socket(zmq.SUB)
socket.connect("tcp://localhost:5555")
socket.setsockopt_string(zmq.SUBSCRIBE, '')
while True:
response = socket.recv();
print("response: %s" % response.decode('utf-8'))
server
# -*- coding=utf-8 -*-
import zmq
import time
context = zmq.Context()
socket = context.socket(zmq.PUSH)
socket.bind("tcp://*:5557")
i = 1
while True:
socket.send_string("测试消息:" + str(i))
print("已发送")
time.sleep(1)
i += 1
worker1
# -*- coding=utf-8 -*-
import zmq
context = zmq.Context()
recive = context.socket(zmq.PULL)
recive.connect('tcp://127.0.0.1:5557')
sender = context.socket(zmq.PUSH)
sender.bind('tcp://*:5558')
while True:
data = recive.recv()
print("正在转发..." + data.decode('utf-8'))
sender.send(data)
worker2
# -*- coding=utf-8 -*-
import zmq
context = zmq.Context()
recive = context.socket(zmq.PULL)
recive.connect('tcp://127.0.0.1:5557')
sender = context.socket(zmq.PUSH)
sender.bind('tcp://*:5559')
while True:
data = recive.recv()
print("正在转发..." + data.decode('utf-8'))
sender.send(data)
client1, client2, client3
# -*- coding=utf-8 -*-
import zmq
import sys
context = zmq.Context()
socket = context.socket(zmq.PULL)
socket.connect("tcp://127.0.0.1:5558")
socket.connect("tcp://127.0.0.1:5559")
while True:
response = socket.recv()
print("response: %s" % response.decode('utf-8'))
文章参考:
https://segmentfault.com/a/1190000012010573#articleHeader3
https://zhuanlan.zhihu.com/p/22947038