Chinaunix首页 | 论坛 | 博客
  • 博客访问: 774800
  • 博文数量: 239
  • 博客积分: 60
  • 博客等级: 民兵
  • 技术积分: 1045
  • 用 户 组: 普通用户
  • 注册时间: 2009-03-22 18:25
文章分类

全部博文(239)

文章存档

2019年(9)

2018年(64)

2017年(2)

2016年(26)

2015年(30)

2014年(41)

2013年(65)

2012年(2)

分类: 架构设计与优化

2018-07-31 21:07:23

https://learning-0mq-with-pyzmq.readthedocs.io/en/latest/_images/Queue.png
参考: https://learning-0mq-with-pyzmq.readthedocs.io/en/latest/pyzmq/devices/queue.html
1)queue_device.py

点击(此处)折叠或打开

  1. import zmq

  2. def main():
  3.     try:
  4.         context = zmq.Context(1)
  5.         # Socket facing clients
  6.         frontend = context.socket(zmq.XREP)
  7.         frontend.bind("tcp://*:5559")
  8.         # Socket facing services
  9.         backend = context.socket(zmq.XREQ)
  10.         backend.bind("tcp://*:5560")

  11.         zmq.device(zmq.QUEUE, frontend, backend)
  12.     except Exception as e:
  13.         print (e)
  14.         print ("bringing down zmq device")
  15.     finally:
  16.         pass
  17.         frontend.close()
  18.         backend.close()
  19.         context.term()

  20. if __name__ == "__main__":
  21.     main()


2)queue_server.py

点击(此处)折叠或打开

  1. import zmq
  2. import time
  3. import sys
  4. import random

  5. port = "5560"
  6. context = zmq.Context()
  7. socket = context.socket(zmq.REP)
  8. socket.connect("tcp://localhost:%s" % port)
  9. server_id = random.randrange(1,10005)

  10. while True:
  11.     # Wait for next request from client
  12.     message = socket.recv()
  13.     print ("Received request: ", message)
  14.     time.sleep (1)
  15.     socket.send( ("World from server %s" % server_id).encode('ascii') )


3)queue_client.py

点击(此处)折叠或打开

  1. import zmq
  2. import sys
  3. import random

  4. port = "5559"
  5. context = zmq.Context()
  6. print( "Connecting to server...")
  7. socket = context.socket(zmq.REQ)
  8. socket.connect ("tcp://localhost:%s" % port)
  9. client_id = random.randrange(1,10005)

  10. # Do 10 requests, waiting each time for a response
  11. for request in range (1,10):
  12.     print( "Sending request ", request,"..." )
  13.     socket.send ( ("Hello from %s" % client_id).encode('ascii') )
  14.     # Get the reply.
  15.     message = socket.recv()
  16.     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) |
给主人留下些什么吧!~~