Chinaunix首页 | 论坛 | 博客
  • 博客访问: 779761
  • 博文数量: 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-08-01 09:52:22

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

点击(此处)折叠或打开

  1. import zmq

  2. def main():
  3.     try:
  4.         context = zmq.Context(1)
  5.         # Socket facing clients
  6.         frontend = context.socket(zmq.SUB)
  7.         frontend.bind("tcp://*:5559")

  8.         frontend.setsockopt(zmq.SUBSCRIBE, "".encode('ascii'))

  9.         # Socket facing services
  10.         backend = context.socket(zmq.PUB)
  11.         backend.bind("tcp://*:5560")

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

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


2)forwarder_subscriber.py

点击(此处)折叠或打开

  1. import sys
  2. import zmq

  3. port = "5560"
  4. # Socket to talk to server
  5. context = zmq.Context()
  6. socket = context.socket(zmq.SUB)
  7. print ("Collecting updates from server...")
  8. socket.connect ("tcp://localhost:%s" % port)
  9. topicfilter = "9".encode('ascii')
  10. socket.setsockopt(zmq.SUBSCRIBE, topicfilter)

  11. for update_nbr in range(10):
  12.     string = socket.recv()
  13.     topic, messagedata = string.split()
  14.     print (topic, messagedata)


3)forwarder_server.py

点击(此处)折叠或打开

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

  5. port = "5559"
  6. context = zmq.Context()
  7. socket = context.socket(zmq.PUB)
  8. socket.connect("tcp://localhost:%s" % port)
  9. publisher_id = random.randrange(0,9999)
  10. while True:
  11.     topic = random.randrange(1,10)
  12.     messagedata = "server#%s" % publisher_id
  13.     print ("%s %s" % (topic, messagedata))
  14.     socket.send( ("%d %s" % (topic, messagedata)).encode('ascii') )
  15.     time.sleep(1)

#python3 forwarder_device.py
#python3 forwarder_subscriber.py
#python3 forwarder_server.py
#python3 forwarder_server.py
阅读(1198) | 评论(0) | 转发(0) |
给主人留下些什么吧!~~