I am using a windows 7 machine with Python 2.7 to make a simple Client/Server ZMQ proof of concept. I ran into this scenario where the listening socket(Server side of the app) is already in use and this throws "zmq.error.ZMQError: Address in use" error.
How do you think is the best way to avoid this error? I was thinking of, when binding the socket catch this error and if error is thrown restart the context and the socket. This is not working, is still throws and error when binding. Server code:
class ZMQServer:
context = None
socket = None
def __init__(self, port):
self.context = zmq.Context()
self.socket = self.context.socket(zmq.REP)
try:
self.socket.bind("tcp://*:"+str(port))
except zmq.error.ZMQError:
print ("socket already in use, restarting")
self.socket.close()
self.context.destroy()
self.context = zmq.Context()
self.socket = self.context.socket(zmq.REP)
self.socket.bind("tcp://*:"+str(port))
I tried another approach, instead of checking the availability of the socket, I am trying to manage it correclty, to do this:
In the socket binding I only catch the ZMQError and display it, I didn;t find a way to fix the blocked socked there.
The recv method that receives the messages is NON-blocking
So, the code now looks like this:
"
import time
import zmq
import threading
class ZMQServer:
context = None
socket = None
alive = False
ZMQthread = None
def __init__(self, port):
self.context = zmq.Context()
self.socket = self.context.socket(zmq.REP)
try:
self.socket.bind("tcp://*:"+str(port))
except zmq.error.ZMQError:
print ("socket already in use, try restarting it")
self.alive = False
self.alive = True
def StartAsync(self):
self.alive = True
ZMQthread = threading.Thread(target=self.Start)
ZMQthread.start()
def Start(self):
while self.alive == True:
# Wait for next request from client
print("Wait for next request from client")
try:
message = self.socket.recv(zmq.NOBLOCK)
print("Received request: %s" % message)
# Do some 'work'
time.sleep(1)
# Send reply back to client
self.socket.send(b"World")
except:
print "no message received in time. trying again"
def CloseServer(self):
print("Stoping the server")
self.alive = False
if(self.socket.closed == False):
self.socket.close()
if self.ZMQthread and self.ZMQthread.is_alive() == True:
self.ZMQthread.join()
if __name__ == '__main__':
zmqServer = ZMQServer(5555)
zmqServer.StartAsync()
time.sleep(20)
zmqServer.CloseServer()
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.