Skip to content

Instantly share code, notes, and snippets.

@sooop
Last active May 3, 2021 14:13
Show Gist options
  • Save sooop/2fed4e0d48d98c634a7f5d628311b1b3 to your computer and use it in GitHub Desktop.
Save sooop/2fed4e0d48d98c634a7f5d628311b1b3 to your computer and use it in GitHub Desktop.
transfering data via pickle and filter with subscribe options with ZMQ PUB-SUB pattern
import io
import pickle
import random
import time
from multiprocessing import Process
import zmq
def pub_main(port=7777):
ctx = zmq.Context()
sock = ctx.socket(zmq.PUB)
sock.bind(f"tcp://*:{port}")
time.sleep(0.2)
while True:
ch = str(random.randint(100, 999)).encode()
data = {"x": random.random(), "y": random.random()}
payload = pickle.dumps(data)
sock.send_multipart([ch, payload])
time.sleep(0.01)
def sub_main(ch=333, port=7777):
ctx = zmq.Context()
sock = ctx.socket(zmq.SUB)
sock.setsockopt(zmq.SUBSCRIBE, str(ch).encode())
sock.connect(f"tcp://localhost:{port}")
for _ in range(100):
_, payload = sock.recv_multipart()
data = pickle.load(io.BytesIO(payload))
print(data)
def main():
pA = Process(target=pub_main)
pA.start()
pB = Process(target=sub_main)
pB.start()
pB.join()
pA.kill()
if __name__ == "__main__":
main()
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment