Skip to content

Instantly share code, notes, and snippets.

@tomasbedrich

tomasbedrich/pub.py

Created Feb 17, 2016
Embed
What would you like to do?
ZMQ demo
#!/usr/bin/env python3
import zmq
import struct
import sys
from time import sleep
def publish(port):
address = "tcp://*:{}".format(port)
i = 0
# open ZMQ socket
context = zmq.Context()
socket = context.socket(zmq.PUB) # set as publisher
socket.bind(address)
print("publisher started")
try:
while True:
# publish message
socket.send(struct.pack("1i", i))
print("published {}".format(i))
i += 1
sleep(1)
except KeyboardInterrupt:
print("shutdown")
# close ZMQ socket
socket.close()
if __name__ == "__main__":
publish(sys.argv[1])
#!/usr/bin/env python3
import zmq
import struct
import sys
def subscribe(host, port):
address = "tcp://{}:{}".format(host, port)
# open ZMQ socket
context = zmq.Context()
socket = context.socket(zmq.SUB) # set as subscriber
socket.connect(address)
socket.setsockopt(zmq.SUBSCRIBE, b"")
print("subscriber started")
try:
while True:
# receive message
raw_data = socket.recv()
i, *_ = struct.unpack("1i", raw_data)
print("got {}".format(i))
except KeyboardInterrupt:
print("shutdown")
# close ZMQ socket
socket.close()
if __name__ == "__main__":
subscribe(sys.argv[1], sys.argv[2])
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
You can’t perform that action at this time.