This article mainly introduces the usage of asyncore in Python. asyncore provides a convenient network operation method. This article describes how to connect and parse the www.python.org homepage, for more information about how to use the asyncore module in python, see the following example. The specific method is as follows:
The instance code is as follows:
# Asyncore import asyncore, socket ####################################### ################################# class AsyncGet (asyncore. dispatcher): "the defined class" "# javasdef _ 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.html HTTP/1.0 \ r \ n" self. outf = None print "connection:", host def handle_connect (self): print 'connect: ', self. host pass def handle_read (self): if not self. outf: print 'connection: ', self. host self. outf = open ("cmds.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. 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") asyncore. loop () import asyncore, socket ####################################### ################################# class AsyncGet (asyncore. dispatcher): "the defined class" "# javasdef _ 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.html HTTP/1.0 \ r \ n" self. outf = None print "connection:", host def handle_connect (self): print 'connect: ', self. host pass def handle_read (self): if not self. outf: print 'connection: ', self. host self. outf = open ("cmds.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. 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") asyncore. loop ()
The content of the result file is:
302 FoundFoundThe document has moved here.
Apache/2.2.16 (Debian) Server at dinsdale.python.org Port 80
I hope this article will help you with Python programming.