2015-09-10 19 views
0

我想做一個使用Tornado的非阻塞的web應用程序。 即應用使用PeriodicCallback作爲調度用於抓取從新聞網站中的數據:tornado回調期間的回調和套接字操作

for nc_uuid in self.LIVE_NEWSCOLLECTORS.keys(): 
      self.LIVE_NEWSCOLLECTORS[nc_uuid].agreggator,ioloop=args 
      period=int(self.LIVE_NEWSCOLLECTORS[nc_uuid].period)*60 
      if self.timer is not None: period = int(self.timer) 

      #self.scheduler.add_job(func=self.LIVE_NEWSCOLLECTORS[nc_uuid].getNews,args=[self.source,i],trigger='interval',seconds=10,id=nc_uuid) 
      task = tornado.ioloop.PeriodicCallback(lambda:self.LIVE_NEWSCOLLECTORS[nc_uuid].getNews(self.source,i),1000*10,ioloop) 
      task.start() 

「的getData」被調用作爲回調具有解析,並通過調用方法process_responce發送的數據到TCPSERVER用於分析一個異步http請求:

@gen.coroutine 
def process_response(self,*args,**kwargs): 
buf = {'sentence':str('text here')} 
data_string = json.dumps(buf) 
s.send(data_string) 
while True: 
    try: 
     data = s.recv(100000) 
     if not data: 
       print "connection closed" 
       s.close() 
       break 
     else: 
      print "Received %d bytes: '%s'" % (len(data), data) 
      # s.close() 
      break 
    except socket.error, e: 
      if e.args[0] == errno.EWOULDBLOCK: 
       print 'error',errno.EWOULDBLOCK 
       time.sleep(1)   # short delay, no tight loops 
      else: 
       print e 
       break 
    i+=1 

Inside process_response我使用非阻塞套接字操作的基本示例。 Process_response顯示如下: 錯誤10035 錯誤10035 收到75字節:'{「mode」:1,「keyword」:「\ u0435 \ u0432 \ u0440 \ u043e」,「sentence」:「text here」} '

看起來很正常的行爲。但是當接收數據時,主IOLoop被鎖定!如果我問網絡服務器它不會返回我的anydata,直到periodiccallback任務完成... 我的錯誤在哪裏?

回答

0

time.sleep()是一個阻塞函數,絕不能在非阻塞代碼中使用。改爲使用yield gen.sleep()

還考慮使用tornado.iostream.IOStream而不是原始套接字操作。