Python中asyncore的用法实例
本文实例讲述了python中asyncore模块的用法,分享给大家供大家参考。具体方法如下:
实例代码如下:
##asyncore importasyncore,socket ######################################################################## classAsyncGet(asyncore.dispatcher): """ thedefinedclass """ #---------------------------------------------------------------------- def__init__(self,host): """Constructor""" asyncore.dispatcher.__init__(self) self.host=host self.create_socket(socket.AF_INET,socket.SOCK_STREAM) self.connect((host,80)) self.request="Get/index.htmlHTTP/1.0\r\n\r\n" self.outf=None print"连接:",host defhandle_connect(self): print'connect:',self.host pass defhandle_read(self): ifnotself.outf: print'正在连接:',self.host self.outf=open("%s.txt"%self.host,'wb') data=self.recv(8192) ifdata: self.outf.write(data) pass defhandle_writebale(self): returnlen(self.request) defhandle_write(self): num_sent=self.send(self.request) pass defhandle_close(self): asyncore.dispatcher.close(self) print"socketclosein:",self.host ifself.outf: self.outf.close() pass if__name__=="__main__": AsyncGet("www.python.org") asyncore.loop() importasyncore,socket ######################################################################## classAsyncGet(asyncore.dispatcher): """ thedefinedclass """ #---------------------------------------------------------------------- def__init__(self,host): """Constructor""" asyncore.dispatcher.__init__(self) self.host=host self.create_socket(socket.AF_INET,socket.SOCK_STREAM) self.connect((host,80)) self.request="Get/index.htmlHTTP/1.0\r\n\r\n" self.outf=None print"连接:",host defhandle_connect(self): print'connect:',self.host pass defhandle_read(self): ifnotself.outf: print'正在连接:',self.host self.outf=open("%s.txt"%self.host,'wb') data=self.recv(8192) ifdata: self.outf.write(data) pass defhandle_writebale(self): returnlen(self.request) defhandle_write(self): num_sent=self.send(self.request) pass defhandle_close(self): asyncore.dispatcher.close(self) print"socketclosein:",self.host ifself.outf: self.outf.close() pass if__name__=="__main__": AsyncGet("www.python.org") asyncore.loop()
结果文件的内容为:
<!DOCTYPEHTMLPUBLIC"-//IETF//DTDHTML2.0//EN"> <html><head> <title>302Found</title> </head><body> <h1>Found</h1> <p>Thedocumenthasmoved<ahref="http://www.python.org">here</a>.</p> <hr> <address>Apache/2.2.16(Debian)Serveratdinsdale.python.orgPort80</address> </body></html>
希望本文所述对大家的Python程序设计有所帮助。