如何在coreclty中解决ZMQ套接字错误" zmq.error.ZMQError:正在使用的地址"在python中

时间:2016-09-05 13:19:26

标签: python sockets pyzmq


我正在使用带有Python 2.7的Windows 7机器来制作简单的客户端/服务器ZMQ概念验证。我遇到了这种情况,其中监听套接字(应用程序的服务器端)已经在使用,并抛出" zmq.error.ZMQError:正在使用的地址"错误。
您认为如何避免此错误的最佳方法?我在考虑,当绑定套接字时捕获此错误,如果抛出错误,请重新启动上下文和套接字。这不起作用,绑定时仍然会引发错误。服务器代码:

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))

1 个答案:

答案 0 :(得分:0)

我尝试了另一种方法,而不是检查套接字的可用性,我试图管理它的相关性,这样做:

  • 在一个单独的线程上创建了侦听器异步。
  • 创建了一个在退出时关闭套接字的方法
  • 在套接字绑定中我只捕获ZMQError并显示它,我没有找到一种方法来修复被阻塞的袜子。

  • 接收消息的recv方法是NON-blocking

所以,代码现在看起来像这样:

"

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()