This article illustrates the use of Asyncore modules in Python and shares them for your reference. The specific methods are as follows:
The instance code is as follows:
# #asyncore Import Asyncore,socket ######################################################################## class A Syncget (Asyncore.dispatcher): "" "" The Defined Class "" #--------------------------------------------------- -------------------def __init__ (self, host): "" Constructor "" "Asyncore.dispatcher.__init__ (self) self. Host = Host Self.create_socket (socket.af_inet, socket.
SOCK_STREAM) Self.connect (host,) self.request = "Get/index.html http/1.0\r\n\r\n" Self.outf = None Print "Connection:", host Def Handle_connect (self): print ' Connect: ', Self.host pass def handle_read (sel f): If not self.outf:print ' is connecting: ', self.host self.outf = open ("%s.txt"% self.host, ' WB ') data = SE LF.RECV (8192) if Data:self.outf.write (data) pass Def Handle_writebale (self): return len (SE Lf.request def handle_write (self): Num_sent = Self.send (self.requeST) Pass def Handle_close (self): Asyncore.dispatcher.close (self) print "socket Close in:", Self.host If Self.outf:self.outf.close () pass if __name__ = = "__main__": Asyncget ("www.python.org") asy Ncore.loop () Import Asyncore,socket ######################################################################## class Asyncget (Asyncore.dispatcher): "" "" The Defined Class "" #------------------------------------------------- ---------------------def __init__ (self, host): "" Constructor "" "Asyncore.dispatcher.__init__ (self) SEL F.host = Host Self.create_socket (socket.af_inet, socket.
SOCK_STREAM) Self.connect (host,) self.request = "Get/index.html http/1.0\r\n\r\n" Self.outf = None Print "Connection:", host Def Handle_connect (self): print ' Connect: ', Self.host pass def handle_read (sel f): If not self.outf:print ' is connecting: ', self.host self.outf = open ("%s.txT "% self.host, ' WB ') data = SELF.RECV (8192) if Data:self.outf.write (data) pass DEF handle _writebale (self): return Len (self.request) def handle_write (self): Num_sent = Self.send (self.requ
EST) pass def handle_close (self): Asyncore.dispatcher.close (self) print "socket Close in:", Self.host If Self.outf:self.outf.close () pass if __name__ = = "__main__": Asyncget ("www.python.org") as
Yncore.loop ()
The contents of the resulting file are:
<! DOCTYPE HTML PUBLIC "-//ietf//dtd HTML 2.0//en" >
I hope this article will help you with your Python programming.