Created
April 25, 2024 11:31
-
-
Save luissimas/fac9f45c4669f5250ae7204347790a90 to your computer and use it in GitHub Desktop.
ZMQ pub sub
This file contains hidden or 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
import logging | |
import random | |
import time | |
from threading import Thread | |
import zmq | |
logging.basicConfig(encoding="utf-8", level=logging.DEBUG) | |
logger = logging.getLogger(__name__) | |
context = zmq.Context() | |
logger.info("Connecting to broker…") | |
pub_socket = context.socket(zmq.PUB) | |
sub_socket = context.socket(zmq.SUB) | |
pub_socket.connect("tcp://localhost:4000") | |
sub_socket.connect("tcp://localhost:4001") | |
logger.info("Connected to broker!") | |
name = input("Username: ") | |
topic = input("Topic: ") | |
sub_socket.setsockopt(zmq.SUBSCRIBE, topic.encode()) | |
def recv(): | |
while True: | |
msg = sub_socket.recv_multipart() | |
logger.info("Received msg %s", msg) | |
def publish(): | |
while True: | |
msg = input("> ") | |
time.sleep(random.random()) | |
logger.info("Sending msg %s", msg) | |
pub_socket.send_multipart([topic.encode(), (f"{name}: {msg}").encode()]) | |
recv_thread = Thread(target=recv) | |
pub_thread = Thread(target=publish) | |
recv_thread.start() | |
pub_thread.start() | |
recv_thread.join() | |
pub_thread.join() |
This file contains hidden or 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
import logging | |
import zmq | |
logging.basicConfig(encoding="utf-8", level=logging.DEBUG) | |
logger = logging.getLogger(__name__) | |
context = zmq.Context() | |
topic = b"messages" | |
logger.info("Binding to sockets") | |
pub_socket = context.socket(zmq.PUB) | |
sub_socket = context.socket(zmq.SUB) | |
sub_socket.bind("tcp://*:4000") | |
pub_socket.bind("tcp://*:4001") | |
sub_socket.setsockopt(zmq.SUBSCRIBE, topic) | |
logger.info("Bound sockets!") | |
# The broker just publishes everything it receives | |
while True: | |
msg = sub_socket.recv_multipart() | |
logger.info("Received msg %s", msg) | |
pub_socket.send_multipart(msg) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Capturing webcam video and saving to a file