33 lines
899 B
Python
33 lines
899 B
Python
import zmq
|
|
import sys
|
|
import time
|
|
import random
|
|
|
|
port = "5556"
|
|
if len(sys.argv) > 1:
|
|
port = sys.argv[1]
|
|
int(port)
|
|
|
|
# Make a context which we use to make sockets from
|
|
context = zmq.Context()
|
|
# Make a new socket. We want to publish on this socket.
|
|
socket = context.socket(zmq.PUB)
|
|
# Bind the socket (inside our program) to a port (on our machine)
|
|
# We can now send messages
|
|
socket.bind(f"tcp://*:{port}")
|
|
|
|
topics = ('TIME', 'RANDOM')
|
|
messages = {}
|
|
while True:
|
|
# Time to publish the latest time!
|
|
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.
|
|
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)
|