Skip to content

Instantly share code, notes, and snippets.

@Dansyuqri
Created April 12, 2020 08:09
Show Gist options
  • Save Dansyuqri/3b533d0f11f3ddd53da34686434309d7 to your computer and use it in GitHub Desktop.
Save Dansyuqri/3b533d0f11f3ddd53da34686434309d7 to your computer and use it in GitHub Desktop.
Multiple Subscribers to One Publisher
# 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()
# 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