Skip to content

Instantly share code, notes, and snippets.

@Dansyuqri
Last active April 12, 2020 10:01
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save Dansyuqri/93b8df592946cf5ec2158aa10c13bbcc to your computer and use it in GitHub Desktop.
Save Dansyuqri/93b8df592946cf5ec2158aa10c13bbcc to your computer and use it in GitHub Desktop.
Single Subscriber to Multiple Publishers
# multi_pub.py
import time
import zmq
from threading import Thread
host = "127.0.0.1"
port = "5001"
ctx = zmq.Context()
def update_smart_mirror(appliance):
socket = ctx.socket(zmq.PUB)
socket.connect(f"tcp://{host}:{port}")
time.sleep(1)
status = {"status": True}
# Sends multipart message to subscriber
socket.send_string(appliance, flags=zmq.SNDMORE)
socket.send_json(status)
coffee_maker = Thread(target=update_smart_mirror, args=("COFFEE MAKER",))
toaster = Thread(target=update_smart_mirror, args=("TOASTER",))
coffee_maker.start()
toaster.start()
# waits for both to send messages before exiting
coffee_maker.join()
toaster.join()
# simple_poller.py
import zmq
host = "127.0.0.1"
port = "5001"
# Creates a socket instance
context = zmq.Context()
socket = context.socket(zmq.SUB)
# Binds the socket to a predefined port on localhost
socket.bind(f"tcp://{host}:{port}")
# Subscribes to the coffee maker and toaster topic
socket.subscribe("COFFEE MAKER")
socket.subscribe("TOASTER")
poller = zmq.Poller()
poller.register(socket, zmq.POLLIN)
while True:
evts = dict(poller.poll(timeout=100))
if socket in evts:
topic = socket.recv_string()
status = socket.recv_json()
print(f"Topic: {topic} => {status}")
# single_sub.py
import time
import zmq
host = "127.0.0.1"
port = "5001"
# Creates a socket instance
context = zmq.Context()
socket = context.socket(zmq.SUB)
# Binds the socket to a predefined port on localhost
socket.bind(f"tcp://{host}:{port}")
# Subscribes to the coffee maker and toaster topic
socket.subscribe("COFFEE MAKER")
socket.subscribe("TOASTER")
while True:
topic = socket.recv_string()
status = socket.recv_json()
print(f"Topic: {topic} => {status}")
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment