How to close a ZMQ socket correctly?

25 Views Asked by At
class ClientThread(MyThread):
    def __init__(self, context, frame):
        MyThread.__init__(self, context, frame)
        self._stop_event = None

    def run(self):
        self._socket = self._context.socket(zmq.SUB)
        address = 'tcp://localhost:5566'
        self._socket.connect(address)
        self._frame.append_info(f'Connect to address: {address}')

        self._socket.setsockopt(zmq.SUBSCRIBE, ''.encode('utf-8'))
        self._loop = True
        while self._loop:
        # self._stop_event = threading.Event()
        # while not self._stop_event.is_set():
            response = self._socket.recv()
            self._frame.append_info(f'Pub msg: {response}')

            if response.decode('utf-8') == 'exit':
                break

        self._socket.close()
        self._socket = None
        print('Client socket close.')

    def close(self):
        self._loop = False
        # self._socket.close()
        # self._stop_event.set()

I use the PUB-SUB model. I want to close the socket correctly.

I have used different ways to close the socket, but there always was some error.

  1. Use the loop flag
  2. Stop the socket directly
  3. Use threading.Event()
0

There are 0 best solutions below