重新连接ZMQ feed在断开后

3

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

#!/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还很新,能指点一下方向就好了。=)


动态DNS?ZeroMQ只会解析一次,这可能是你的问题。 - Steve-o
我使用动态DNS。我有一个.it.cx主机名指向我的IP地址,该地址定期在我的路由器上更新。是否有任何方法可以通过循环检查连接是否存在,如果不存在则尝试重新连接? - blitzmann
你需要定期关闭并重新连接以重新解析DNS条目。 - Steve-o
1个回答

3

不确定这是否仍然相关,但是请看以下内容:

使用超时(例如这里, 这里这里)。在 ZMQ < 3.0 中,它看起来像是这样的(未经测试):

#!/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()

ZMQ > 3.0允许您设置套接字的RCVTIMEO选项,这将导致其recv()在没有Poller对象需要的情况下引发超时错误。


网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接