Python Learning asyncore module usages Tutorial _python

Source: Internet
Author: User
Tags readable in python

In this paper, the principle and usage of Asyncore module in Python are analyzed and shared for everyone's reference. The specific analysis is as follows:

The Asyncore library is a standard library of Python, which is the wrapper of an asynchronous socket. When we operate the network can directly use the socket, such as the bottom of the library, but Asyncore makes it easier to operate the network, to avoid the direct use of socket,select,poll and other tools need to face the complexity.

This library is simple, contains a function and a class
* Loop () function
* Dispatcher base class
It should be noted that the loop function is global, not a dispatcher method

The object of each class that inherits from dispatcher can be seen as a socket we need to deal with, either as a TCP connection or UDP, or even something else that is not commonly used. Easy to use, we need to define a class, it inherits dispatcher, and then we rewrite (overwrite) some methods on it.

The methods we need to rewrite are generally preceded by Handle_.

Class Refuse (Dispatcher):
  def handle_accept ():
    #do nothing ...
    Pass

The loop () function is responsible for detecting an instance of the saved dispatcher in a dict,dict, which is called Channel. Each time you create a Dispatcher object, you add yourself to a default Dict (you can also specify channel yourself). When an object is added to the channel, the behavior of the socket is defined, and the program only needs to call loop (), and all functions are implemented.

Asyncore is a good design in the Python standard library
In the standard Python document, there is an example of a asyncore

Import Asyncore, Socket
class Http_client (Asyncore.dispatcher):
  def __init__ (self, Host, path):
    Asyncore.dispatcher.__init__ (self)
    self.create_socket (socket.af_inet, socket. SOCK_STREAM)
    Self.connect (host,)
    Self.buffer = ' Get%s http/1.0\r\n\r\n '% path
  def handle_connect ( Self):
    pass
  def handle_close (self):
    self.close ()
  def handle_read (self):
    print Self.recv ( 8192
  def writable (self): return
    (len (Self.buffer) > 0)
  def handle_write (self):
    sent = Self.send (self.buffer)
    Self.buffer = self.buffer[sent:]
c = http_client (' www.python.org ', '/')
Asyncore.loop ()

Running this function, we found that Python.org's homepage was downloaded, which means we implemented an HTTP layer protocol? But we only use the socket-level API ... So take a look at the mystery of these lines of code!

Writable and readable are invoked when a socket can be written or detected to arrive, and a bool is returned to determine whether Handle_read or Handle_write

Open asyncore.py You can see that the methods defined in the dispatcher class writable and readable are fairly simple to define:

def readable (self): return
  true
def writable (self): return
  True

That is, once readable or writable is detected, call Handle_read/handle_write directly, but in the example above, we see an overload (which looks like a virtual function of C + +), doesn't it? )

def writable (self): return
  (len (Self.buffer) > 0)

Obviously, when we have the data to send, we give the writable caller a true, so there is no need to do in the Handle_write, the logic is clear, the code is very clear, the ointment is that understanding needs a little time, but not difficult it!

The rest of the code looks very clear, there is a kind of soldier to block the feeling. When an HTTP server sends processing to complete your request, close socket, our handle_close () also completes its mission accordingly. Close () Deletes the object itself from the channel and is responsible for destroying the socket object.

def close (self):
  self.del_channel ()
  self.socket.close ()

The loop () function detects an empty channel, will exit the loop, the program completes the task, exit.

I hope this article will help you with your Python programming.

Related Article

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.