参考: https://learning-0mq-with-pyzmq.readthedocs.io/en/latest/pyzmq/devices/forwarder.html
1)forwarder_device.py
-
import zmq
-
-
def main():
-
try:
-
context = zmq.Context(1)
-
# Socket facing clients
-
frontend = context.socket(zmq.SUB)
-
frontend.bind("tcp://*:5559")
-
-
frontend.setsockopt(zmq.SUBSCRIBE, "".encode('ascii'))
-
-
# Socket facing services
-
backend = context.socket(zmq.PUB)
-
backend.bind("tcp://*:5560")
-
-
zmq.device(zmq.FORWARDER, 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)forwarder_subscriber.py
-
import sys
-
import zmq
-
-
port = "5560"
-
# Socket to talk to server
-
context = zmq.Context()
-
socket = context.socket(zmq.SUB)
-
print ("Collecting updates from server...")
-
socket.connect ("tcp://localhost:%s" % port)
-
topicfilter = "9".encode('ascii')
-
socket.setsockopt(zmq.SUBSCRIBE, topicfilter)
-
-
for update_nbr in range(10):
-
string = socket.recv()
-
topic, messagedata = string.split()
-
print (topic, messagedata)
3)forwarder_server.py
-
import zmq
-
import random
-
import sys
-
import time
-
-
port = "5559"
-
context = zmq.Context()
-
socket = context.socket(zmq.PUB)
-
socket.connect("tcp://localhost:%s" % port)
-
publisher_id = random.randrange(0,9999)
-
while True:
-
topic = random.randrange(1,10)
-
messagedata = "server#%s" % publisher_id
-
print ("%s %s" % (topic, messagedata))
-
socket.send( ("%d %s" % (topic, messagedata)).encode('ascii') )
-
time.sleep(1)
#python3 forwarder_device.py
#python3 forwarder_subscriber.py
#python3 forwarder_server.py
#python3 forwarder_server.py
阅读(1181) | 评论(0) | 转发(0) |