From 7685c36677db532359e8125af943eabebc95dceb Mon Sep 17 00:00:00 2001 From: DBras Date: Thu, 13 Jun 2024 11:29:57 +0200 Subject: [PATCH] step 2.3: multiple topics --- pubsub/pub_server.py | 14 ++++++++++---- pubsub/sub_client.py | 5 +++-- 2 files changed, 13 insertions(+), 6 deletions(-) diff --git a/pubsub/pub_server.py b/pubsub/pub_server.py index fb096fe..b0702b8 100644 --- a/pubsub/pub_server.py +++ b/pubsub/pub_server.py @@ -1,6 +1,7 @@ import zmq import sys import time +import random port = "5556" if len(sys.argv) > 1: @@ -15,12 +16,17 @@ socket = context.socket(zmq.PUB) # We can now send messages socket.bind(f"tcp://*:{port}") -topic = "TIME" +topics = ('TIME', 'RANDOM') +messages = {} while True: # Time to publish the latest time! - messagedata = time.ctime() + messages['TIME'] = time.ctime() + messages['RANDOM'] = random.randint(1,10) # Note the use of XXX_string here; # the non-_stringy methods only work with bytes. - socket.send_string(f"{topic};{messagedata}") - print(f"Published topic {topic}: {messagedata}") + for topic in topics: + message = messages.get(topic, '') + if not message: continue + socket.send_string(f"{topic};{message}") + print(f"Published topic {topic}: {message}") time.sleep(1) diff --git a/pubsub/sub_client.py b/pubsub/sub_client.py index a3ce0a9..8834ae3 100644 --- a/pubsub/sub_client.py +++ b/pubsub/sub_client.py @@ -15,8 +15,9 @@ print(f"Collecting updates from time server at tcp://localhost:{port}") socket.connect(f"tcp://{ip}:{port}") # Filter by topic -topicfilter = "TIME" -socket.setsockopt_string(zmq.SUBSCRIBE, topicfilter) +topicfilters = ("TIME", "RANDOM") +socket.setsockopt_string(zmq.SUBSCRIBE, topicfilters[0]) +socket.setsockopt_string(zmq.SUBSCRIBE, topicfilters[1]) # Process 5 updates topic_list = []