Last active
April 12, 2020 10:01
-
-
Save Dansyuqri/93b8df592946cf5ec2158aa10c13bbcc to your computer and use it in GitHub Desktop.
Single Subscriber to Multiple Publishers
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
# 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() |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
# 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}") |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
# 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