step 2.3: multiple topics

This commit is contained in:
DBras 2024-06-13 11:29:57 +02:00
parent 1044d6224a
commit 7685c36677
2 changed files with 13 additions and 6 deletions

View File

@ -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)

View File

@ -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 = []