Created
February 17, 2016 19:24
-
-
Save tomasbedrich/446eac05ad24e63dd08e to your computer and use it in GitHub Desktop.
ZMQ demo
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
#!/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]) |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
#!/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