检测断开持久的curl连接。

4
我应该在哪里检查pycurl持久连接的断开?
在我的脚本中,连接会中断/超时/抛出错误,但脚本仍然保持打开状态。我需要检测问题,以便重新启动脚本。
我们正在连接到gnip(社交媒体数据提供商)。
我的代码在这里:https://gist.github.com/3353033 我已经阅读了libcurl的选项,并阅读了php curl_setopts文档,因为它们也利用了libcurl。
class Client:  
    time_start = time.time()
    content = ""
    def __init__(self,options):
        self.options = options  
        self.buffer = ""  
        self.conn = pycurl.Curl()  
        self.conn.setopt(pycurl.USERPWD, "%s:%s" % (USER, PASS))  
        self.conn.setopt(pycurl.ENCODING,'gzip')
        self.conn.setopt(pycurl.URL, STREAM_URL)  
        self.conn.setopt(pycurl.WRITEFUNCTION, self.on_receive)  
        self.conn.setopt(pycurl.FOLLOWLOCATION,1)
        self.conn.setopt(pycurl.MAXREDIRS, 5)
        self.conn.setopt(pycurl.COOKIEFILE,"cookie.txt")
        try:
            self.conn.perform()  
        except Exception,e:
            print e.message

    def on_receive(self, data):
        self.buffer += data  

        if data.endswith("\r\n") and self.buffer.strip():  
            if(self.triggered()):
                if(len(self.buffer) != 0 ):
                    try:
                        SaveThread(self.buffer).start()
                    except Exception, e:
                        print "something i commented would have told you there was an error"
                        system.exit(1) 
                self.buffer = ""

    def triggered(self):
        # First trigger based on size then based on time..
        if (len(self.buffer) > SAVE_FILE_LENGTH):
            return True
        time_end = time.time()
        if (((time_end - self.time_start) > ROLL_DURATION)):  #for the time frame 
            self.time_start=time.time()
            return True
        return False

编辑:我已经修复了代码片段


你的代码片段缩进不正确。我建议你在这里发布你的源代码。 - stderr
@MikeSteder 我相信我已经修复了这个要点,我已经将它复制到这里。谢谢! - Jake
1个回答

0
在上面的代码中,system.exit(1) 应该改为 sys.exit(1),对吗?
除此之外,您是否还有任何未处理的except子句,可能会捕获由sys.exit(1)引发的SystemExit异常?

我现在没有查看脚本,但我确定那不是问题所在。我们已经找到了解决方案,并计划在接下来的一天左右发布答案。问题的要点是网络连接问题。如果线路中断,那么我们的提供商认为仍应该向管道发送数据,并且它会因缓冲区写入错误而从其端断开连接,在我们这一端,我们正在从空缓冲区读取,并且不知道连接已经断开。我们使用了一些低数据速度/超时选项来克服这个问题,并在低数据量时断开连接。 - Jake
嗨,我们在使用Gnip时遇到了类似的问题。您能否详细说明您的解决方案?我们的代码看起来非常相似。您是如何检测低数据速度的? - Deep Kapadia
@DeepKapadia 设置 LOW_SPEED_LIMIT 和 LOW_SPEED_TIME 选项,当网络流量低于这些限制时,您将收到错误(28)的提示。(请参见:http://curl.haxx.se/libcurl/c/CURLOPT_LOW_SPEED_LIMIT.html) - nickmilon

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