Python script termination when using ZeroMQ with dead server

I have a problem closing a python application when I use ZeroMQ. first connect to a server that is not working!

context = zmq.Context() socket = context.socket(zmq.REQ) socket_id = randomID() socket.setsockopt(zmq.IDENTITY, socket_id) socket.connect("tcp://dead_server") poller = zmq.Poller() poller.register(socket, zmq.POLLIN) 

and sending my message

 socket.send(msg) 

waiting for an answer

 sockets = dict(poller.poll(1000)) if sockets.get(socket) == zmq.POLLIN: result = socket.recv() print (result) 

therefore the server is dead, the message will not be sent and there will be no reply. it's true. then I close the socket and cancel it from poller, and then connect to the live server with a new socket, and I send a message to the socket and get a response from it.

 poller.unregister(socket) socket.close() socket = context.socket(zmq.REQ) socket.setsockopt(zmq.IDENTITY, socket_id) poller.register(socket, zmq.POLLIN) socket.connect("tcp://alive_server") socket.send(msg) sockets = dict(poller.poll(1000)) if sockets.get(socket) == zmq.POLLIN: result = socket.recv() print (result) # Every thing ok up to hear 

after it the application (python script) is not closed (completion)! That's my problem. I can close the application using sig_term , but I will not use it for any reason.] If I do not send the first message to the dead server, the application is closed for real. I think the problem is in ZeroMQ io, but I can not solve it.

 exit(0) # Not worked sys.exit(0) # Not worked 
+6
source share
1 answer

You encounter ZeroMQ LINGER behavior . LINGER defines the timeout for the Context before allowing Context.term discard messages. The default value in ZeroMQ 2.x is eternal, and the default value in ZeroMQ 3.x is one second. If you tell your sockets that they should be delayed for a short time, your script should exit just fine:

 socket = context.socket(zmq.REQ) socket_id = randomID() socket.identity = ramdomID() socket.linger = 250 # 250ms = 1/4 s socket.connect("tcp://dead_server") 
+6
source

Source: https://habr.com/ru/post/947424/


All Articles