断开连接后重新连接到ZMQ源

时间:2013-04-22 22:03:22

标签: 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.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()

这在我的家庭服务器上运行。有时,我的家庭服务器失去了与互联网的连接,这是一个住宅连接的诅咒。然而,当网络辍学并重新开启时,脚本会停止。有没有办法重新初始化连接?我还是蟒蛇新手,正确方向上的一点很精彩。 =)

1 个答案:

答案 0 :(得分:2)

不确定这是否仍然相关,但这里有:

使用超时(示例hereherehere)。在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对象。