2013-04-22 162 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對象。

相關問題