3

我有这个简单的 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 的新手,在正确的方向上一点会很棒。=)

4

1 回答 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对象。

于 2013-08-09T08:35:42.947 回答