51 lines
1.4 KiB
Python
51 lines
1.4 KiB
Python
import sys
|
|
import zmq
|
|
from time import sleep
|
|
|
|
"""
|
|
This version of the subscriber doesn't hang
|
|
"""
|
|
|
|
|
|
ip = "localhost"
|
|
port = "5556"
|
|
if len(sys.argv) > 1:
|
|
port = sys.argv[1]
|
|
int(port)
|
|
|
|
# Make a context we can use to get a socket
|
|
context = zmq.Context()
|
|
# Grab a socket that can connect to the server
|
|
socket = context.socket(zmq.SUB)
|
|
|
|
# Connect to the server by saying where we can get our measurements from
|
|
print(f"Collecting updates from time server at tcp://localhost:{port}")
|
|
socket.connect(f"tcp://{ip}:{port}")
|
|
|
|
# Filter by topic - we are only interested in knowing about the time
|
|
topicfilter = "TIME"
|
|
socket.setsockopt_string(zmq.SUBSCRIBE, topicfilter)
|
|
|
|
# Process 5 updates
|
|
topic_list = []
|
|
# We need to keep track of how many we've received
|
|
# since the loop may end with no messages
|
|
try:
|
|
while len(topic_list) < 5:
|
|
try: # Need to use a try block since zmq uses a
|
|
# giving the flag NOBLOCK indicates to zmq that we don't want to
|
|
# hang waiting for a message.
|
|
string = socket.recv_string(zmq.NOBLOCK)
|
|
except zmq.Again:
|
|
print("No message this time :(")
|
|
continue
|
|
topic, messagedata = string.split(';')
|
|
topic_list.append(messagedata)
|
|
print(f"Received on topic {topic}: {messagedata}")
|
|
#
|
|
finally
|
|
sleep(0.2)
|
|
socket.close()
|
|
t_str = "\n".join(topic_list)
|
|
print(f"All the times we received: \n{t_str}")
|