Python 断开后重新连接到ZMQ馈线

Python 断开后重新连接到ZMQ馈线,python,network-programming,zeromq,pyzmq,Python,Network Programming,Zeromq,Pyzmq,我有一个简单的python脚本,它连接到ZMQ提要并输出一些数据: #!/usr/bin/env python2 import zlib import zmq import simplejson def main(): context = zmq.Context() subscriber = context.socket(zmq.SUB) # Connect to the first publicly available relay. subscriber.c

我有一个简单的python脚本,它连接到ZMQ提要并输出一些数据:

#!/usr/bin/env python2
import zlib
import zmq
import simplejson

def main():
    context = zmq.Context()
    subscriber = context.socket(zmq.SUB)

    # Connect to the first publicly available relay.
    subscriber.connect('tcp://relay-us-east-1.eve-emdr.com:8050')
    # Disable filtering.
    subscriber.setsockopt(zmq.SUBSCRIBE, "")

    while True:
        # Receive raw market JSON strings.
        market_json = zlib.decompress(subscriber.recv())
        # Un-serialize the JSON data to a Python dict.
        market_data = simplejson.loads(market_json)
        # Dump typeID
        results = rowsets = market_data.get('rowsets')[0];
        print results['typeID']

if __name__ == '__main__':
    main()

这是在我的家庭服务器上运行的。有时,我的家庭服务器会失去与互联网的连接,这是住宅连接的诅咒。但是,当网络退出并重新启动时,脚本会暂停。有没有办法重新初始化连接?我对python还是个新手,只要方向正确就好了

不确定这是否仍然相关,但下面是:

使用超时(示例和)。在ZMQ<3.0上,它看起来像这样(未测试):


ZMQ>3.0允许您设置套接字的
RCVTIMEO
选项,这将导致其
recv()
引发超时错误,而无需
轮询器
对象。

动态DNS?ZeroMQ将只解决一次,这可能是您的问题。我使用动态DNS,是的。我有一个.it.cx主机名指向我的IP地址,该地址在我的路由器上定期更新。如果有任何方法可以通过循环检查是否存在连接,如果没有,请尝试重新连接?您需要定期关闭并重新连接以重新解析DNS条目。
#!/usr/bin/env python2
import zlib
import zmq
import simplejson

def main():
    context = zmq.Context()
    while True:
        subscriber = context.socket(zmq.SUB)
        # Connect to the first publicly available relay.
        subscriber.connect('tcp://relay-us-east-1.eve-emdr.com:8050')
        # Disable filtering.
        subscriber.setsockopt(zmq.SUBSCRIBE, "")
        this_call_blocks_until_timeout = recv_or_timeout(subscriber, 60000)
        print 'Timeout'
        subscriber.close()

def recv_or_timeout(subscriber, timeout_ms)
    poller = zmq.Poller()
    poller.register(subscriber, zmq.POLLIN)
    while True:
        socket = dict(self._poller.poll(stimeout_ms))
        if socket.get(subscriber) == zmq.POLLIN:
            # Receive raw market JSON strings.
            market_json = zlib.decompress(subscriber.recv())
            # Un-serialize the JSON data to a Python dict.
            market_data = simplejson.loads(market_json)
            # Dump typeID
            results = rowsets = market_data.get('rowsets')[0];
            print results['typeID']
        else:
            # Timeout!
            return

if __name__ == '__main__':
    main()