2013-04-22 135 views
2

后我有一个连接到ZMQ饲料,吐出了一些数据,这个简单的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很陌生,在正确的方向上的一个点将是美好的。 =)

+0

动态DNS? ZeroMQ只会解决一次,这可能是您的问题。 – 2013-04-23 00:56:26

+0

我使用动态DNS,是的。我有一个.it.cx主机名,指向我的IP地址,并在我的路由器上定期更新。如果有任何方法可以通过循环检查,如果有连接,并且如果不尝试重新连接? – Ryan 2013-04-23 01:26:28

+0

您应定期关闭并重新连接以重新解析DNS条目。 – 2013-04-23 17:24:43

回答

1

不知道这仍然是相关的,但这里有云:

使用超时(例子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对象。