Created
April 12, 2020 08:09
-
-
Save Dansyuqri/3b533d0f11f3ddd53da34686434309d7 to your computer and use it in GitHub Desktop.
Multiple Subscribers to One Publisher
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_sub.py | |
import zmq | |
from threading import Thread | |
host = "127.0.0.1" | |
port = "5001" | |
ctx = zmq.Context() | |
# simple function to receive the 'light' publisher's messages | |
def on_light_status(appliance): | |
socket = ctx.socket(zmq.SUB) | |
socket.connect(f"tcp://{host}:{port}") | |
socket.subscribe("light") | |
light_msg = socket.recv_string() | |
print(f"{appliance} received '{light_msg}' from light.") | |
coffee_maker = Thread(target=on_light_status, args=("COFFEE MAKER",)) | |
toaster = Thread(target=on_light_status, args=("TOASTER",)) | |
coffee_maker.start() | |
toaster.start() | |
# waits for both to receive 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
# single_pub.py | |
import time | |
import zmq | |
host = "127.0.0.1" | |
port = "5001" | |
# Creates a socket instance | |
context = zmq.Context() | |
socket = context.socket(zmq.PUB) | |
# Binds the socket to a predefined port on localhost | |
socket.bind(f"tcp://{host}:{port}") | |
time.sleep(1) | |
# Sends a string message | |
socket.send_string("light is ON") |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment