参考: https://learning-0mq-with-pyzmq.readthedocs.io/en/latest/pyzmq/devices/queue.html
1)
queue_device.py
-
import zmq
-
-
def main():
-
try:
-
context = zmq.Context(1)
-
# Socket facing clients
-
frontend = context.socket(zmq.XREP)
-
frontend.bind("tcp://*:5559")
-
# Socket facing services
-
backend = context.socket(zmq.XREQ)
-
backend.bind("tcp://*:5560")
-
-
zmq.device(zmq.QUEUE, frontend, backend)
-
except Exception as e:
-
print (e)
-
print ("bringing down zmq device")
-
finally:
-
pass
-
frontend.close()
-
backend.close()
-
context.term()
-
-
if __name__ == "__main__":
-
main()
2)queue_server.py
-
import zmq
-
import time
-
import sys
-
import random
-
-
port = "5560"
-
context = zmq.Context()
-
socket = context.socket(zmq.REP)
-
socket.connect("tcp://localhost:%s" % port)
-
server_id = random.randrange(1,10005)
-
-
while True:
-
# Wait for next request from client
-
message = socket.recv()
-
print ("Received request: ", message)
-
time.sleep (1)
-
socket.send( ("World from server %s" % server_id).encode('ascii') )
3)queue_client.py
-
import zmq
-
import sys
-
import random
-
-
port = "5559"
-
context = zmq.Context()
-
print( "Connecting to server...")
-
socket = context.socket(zmq.REQ)
-
socket.connect ("tcp://localhost:%s" % port)
-
client_id = random.randrange(1,10005)
-
-
# Do 10 requests, waiting each time for a response
-
for request in range (1,10):
-
print( "Sending request ", request,"..." )
-
socket.send ( ("Hello from %s" % client_id).encode('ascii') )
-
# Get the reply.
-
message = socket.recv()
-
print ("Received reply ", request, "[", message, "]")
#python3 queue_device.py
#python3 queue_server.py
#python3 queue_server.py
#python3 queue_client.py
#python3 queue_client.py
阅读(1451) | 评论(0) | 转发(0) |