python – asyncore超时
发布时间:2020-12-20 13:25:52 所属栏目:Python 来源:网络整理
导读:简单的异步http客户端,很长时间没有可用的站点. 例如,在网站www.evtur.ru它等待很长时间,十分钟或更长时间. 我找不到如何最小化超时的方法,例如可以在5秒内执行超时吗? # coding=utf-8import asyncoreimport string,socketimport StringIOimport mimetools,
简单的异步http客户端,很长时间没有可用的站点.
例如,在网站www.evtur.ru它等待很长时间,十分钟或更长时间. 我找不到如何最小化超时的方法,例如可以在5秒内执行超时吗? # coding=utf-8 import asyncore import string,socket import StringIO import mimetools,urlparse class AsyncHTTP(asyncore.dispatcher): # HTTP requestor def __init__(self,uri): asyncore.dispatcher.__init__(self) self.uri = uri # turn the uri into a valid request scheme,host,path,params,query,fragment = urlparse.urlparse(uri) assert scheme == "http","only supports HTTP requests" try: host,port = string.split(host,":",1) port = int(port) except (TypeError,ValueError): port = 80 # default port if not path: path = "/" if params: path = path + ";" + params if query: path = path + "?" + query self.request = "GET %s HTTP/1.0rnHost: %srnrn" % (path,host) self.host = host self.port = port self.status = None self.header = None self.http_code = None self.data = "" # get things going! self.create_socket(socket.AF_INET,socket.SOCK_STREAM) #self.connect((host,port)) #return try: self.connect((host,port)) except Exception,e: self.close() self.handle_connect_expt(e) def handle_connect(self): self.send(self.request) def handle_expt(self): print "handle_expt error!" self.close() def handle_error(self): print "handle_error error!" self.close() def handle_connect_expt(self,expt): print "connection error:",expt def handle_code(self): print self.host," : ","recv http code: ",self.http_code def handle_read(self): data = self.recv(2048) #print data if not self.header: self.data = self.data + data try: i = string.index(self.data,"rnrn") except ValueError: return # continue else: # parse header fp = StringIO.StringIO(self.data[:i+4]) # status line is "HTTP/version status message" status = fp.readline() self.status = string.split(status," ",2) self.http_code = self.status[1] self.handle_code() # followed by a rfc822-style message header self.header = mimetools.Message(fp) # followed by a newline,and the payload (if any) data = self.data[i+4:] self.data = "" #header recived #self.close() def handle_close(self): self.close() c = AsyncHTTP('http://www.python.org') c = AsyncHTTP('http://www.evtur.ru') asyncore.loop(timeout=0.05) 解决方法self.socket.settimeout(nn) 这似乎不适合我. 但是,asyncore.loop()具有名为count的参数.这里是伪代码asyncore.loop()在做什么: for i in range(count): ... select(...,timeout) ... 所以如果你想要5秒钟,你需要做: asyncore.loop(timeout=1,count=5) 但不建议以这种方式工作.请注意,如果存在“事件”,则可能有超过5个“计数”.我使用以下代码: start = int(time.time()) while True: asyncore.loop(timeout=1,count=5) print "LOOP : %d enqueued,waiting to finish" % len(asyncore.socket_map) if len(asyncore.socket_map) == 0 : break if int(time.time()) - start > timeout : print "LOOP : Timeout" break (编辑:李大同) 【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容! |