[Python] How to reconnect zeromq client to server?

Discussão em 'Python' iniciado por Stack, Novembro 27, 2025.

  1. Stack

    Stack Membro Participativo

    I have just started using the Python ZeroMQ library, pyzmq==27.1.0.

    I am running on a Raspberry Pi 5 (debian 12 - bookworm)

    I want to make sure my client reconnects if my server stops and restarts. When I run the server first it works fine. But if I run the client first or the server stops and restarts then the client doesn't connect.

    I was hoping it might automatically re-connect, but that doesn't work for me. I keep trying to send and keep getting


    Operation cannot be accomplished in current state
    ​

    even when the server restarts.

    import time
    import zmq

    class Test:
    def __init__(self):
    context = zmq.Context()
    self._socket = context.socket(zmq.REQ)

    # Suggested settings for auto-reconnect
    self._socket.setsockopt(zmq.LINGER, 0)
    self._socket.setsockopt(zmq.RECONNECT_IVL, 1000)
    self._socket.setsockopt(zmq.RECONNECT_IVL_MAX, 5000)

    self._socket.connect(f"tcp://localhost:5555")

    def request(self, request: str) -> str:
    try:
    self._socket.send(request.encode())

    # Get the reply.
    if self._socket.poll(1000, zmq.POLLIN):
    message = self._socket.recv()
    else:
    raise Exception("Machine control service is not responding")
    return message.decode()
    except Exception as ex:
    print("ERROR", ex)


    def run():
    control = Test()

    while True:
    reply = control.request("READALL")
    print("Received reply:", reply)
    time.sleep(1)


    if __name__ == "__main__":
    run()


    I tried disconnecting and re-connecting, but even while the server is down the client appears to connect successfully but cannot send. Then when the server comes up again, it continues to fail to send.

    def __init__(self):
    self._connection_string = f"tcp://localhost:{SERVER_PORT}"
    context = zmq.Context()
    self._socket = context.socket(zmq.REQ)
    self._socket_connected = False
    self._gpio_input_states = ""

    def _connect(self):
    if not self._socket_connected:
    print("connect")
    self._socket.connect(self._connection_string)
    self._socket_connected = True
    print("connected!!!!!")

    def _disconnect(self):
    if self._socket_connected:
    print("disconnect")
    self._socket.disconnect(self._connection_string)
    self._socket_connected = False

    def request(self, request: str) -> str:
    try:
    self._connect()
    self._socket.send(request.encode())

    # Get the reply.
    if self._socket.poll(1000, zmq.POLLIN):
    message = self._socket.recv()
    else:
    raise Exception("Machine control service is not responding")
    return message.decode()
    except Exception as ex:
    self._disconnect()
    raise MachineControlInterfaceException(f"Failed to send request to machine control service. Reason: {ex}")


    Should it be possible to do this? What am I doing wrong?

    Continue reading...

Compartilhe esta Página