Search code examples
pythonzeromq

How to reestablish ROUTER/DEALER connection in ZMQ?


# ROUTER
import time
import random
import zmq
 
context = zmq.Context.instance()
client = context.socket(zmq.ROUTER)
client.setsockopt(zmq.TCP_KEEPALIVE,1)
client.bind("tcp://127.0.0.1:99999")
  
for _ in range(100):
    ident = random.choice([b'A', b'A', b'B'])           
    work = b"This is the workload"
    client.send_multipart([ident, work])
    
    time.sleep(0.5)
#CLIENT
import zmq
   
context =  zmq.Context.instance()
worker = context.socket(zmq.DEALER)
worker.setsockopt(zmq.IDENTITY, b'A')
worker.connect("tcp://127.0.0.1:99999")

while True:
    request = worker.recv()
    print(request)

My goal is to make multiple clients receive data from ROUTER, determined by identities(A, B). It works fine no matter which starts first. However, once a client is halted and restarted, it can't recconnect to ROUTER or receive data anymore. Is this pattern not designed to deal with this or are there options to make a client reconnect ROUTER again?


Solution

  • Are there implications to reconnecting a ZMQ socket with the same identity?

    It needs ROUTER_HANDOVER option

    client.setsockopt(zmq.ROUTER_HANDOVER, 1)