Pythonasyncore asynchronous Io is learned by the Python standard library

Source: Internet
Author: User

#-*-Coding:utf-8-*-

# python:2.x

__author__ = ' Administrator '

Import Asynchat,asyncore,logging,socket

#asyncore Asynchronous IO

# Function: Exception IO processing

# function is to process IO objects, such as sockets, so that they can be managed asynchronously (instead of multiple threads or processes), including the class has dispatcher, which is a socket wrapper, Provides some hooks(hooks) that can handle connections and read-write events when called from the main loop function Loo ()

# Server

# The first class is a echoservr

# It receives the connection from the customer, once the connection is accepted, the demo will be closed and the server can be easier to start and end

Class Echoservr (Asyncore.dispatcher):

def __init__ (self,addres):

Self.logger=logging.getlevelname (' Echoservr ')

Asyncore.dispatcher.__init__ (self)

Self.create_socket (Socket.af_inet,socket. SOCK_STREAM)

Self.bind (addres)

Self.address=self.socket.getsockname ()

Self.logger.debug (' Binding to%s '% (self.address))

Self.listen (1)

def handle_accept (self):

Client_into=self.accept ()

Self.logger.debug (' Accpet ()->%s '% (client_into[1]))

Echohandler (Sock=client_into[0])

Self.handle_close ()

Return

def handle_close (self):

Self.logger.debug (' Handle_close () ')

Return

"""

Handle_accept () each time a new connection is accepted , Echoservr creates a new Echohandler instance to manage the connection. Echohandler , Echoservr

Defined in different classes, because they do different work,Echoservr accepts a full connection to a new socket, not Assigning the socket to a single customer in Echohandler, Instead, it creates a Echohandler

To take full advantage of maintaining socket mappings by Asyncore

"""

Class Echohandler (Asyncore.dispatcher):

def __init__ (self,sock,chunk_size=256):

Self.chunk_size=chunk_size

Logger_name= ' Echohandier '

Self.logger=logging.getlevelname (Logger_name)

asyncore.dispatcher.__init__ (Self,sock=sock)

Self.data_to_write=[]

Return

def writable (self):

Respone=bool (Self.data_to_write)

Self.logger.debug ('%s '% (respone))

Return Respone

def handle_write (self):

Data=self.data_to_write.pop ()

Sent=self.send (Data[:self.chunk_size])

If Sent<len (data):

Remaing=data[sent:]

Self.data_to_write.append (remaing)

Self.logger.debug ('%d%r '% (Sent,data[:sent]))

If not self.writable ():

Self.handle_close ()

def handle_close (self):

Self.logger.debug (' Handle_close () ')

Self.close ()

def handle_read (self):

DATA=SELF.RECV (Self.chunk_size)

Self.logger.debug ('%d%r '% (len (data), data))

Self.data_to_write.insert (0,data)

# Client

# Create a customer based on Asynoce , need to derive dispatcher, and provide implementations to complete socket creation and reading, for echoclient , you can use create_socket () to create sockets in __init__ () , or you can provide other implementations of this method

Class Echoclient (Asyncore.dispatcher):

def __init__ (self,host,port,message,chunk_size=128):

Self.message=message

Self.to_send=message

Self.received_data=[]

Self.chunk_size=chunk_size

Self.logger=logging.getlevelname (' echoclient ')

Asyncore.dispatcher.__init__ (self)

Self.create_socket (Socket.af_inet,socket. SOCK_STREAM)

Self.logger.dubug ('%s '% (Host,port))

Self.connect ((Host,port))

Return

def handle_close (self): #hook just for when it gets called, other types of customers who need to actually connect to the handshake or protocol negotiation, in this way sip the work done

Self.logger.debug (' Handle_close () ')

# The following handle_close () is also used to show when it is called during processing, and the method in the base class correctly closes the socket, which is not required if additional cleanup work should not be done at shutdown .

def handle_close (self):

Self.logger.debug (' Handle_close () ')

Self.close ()

Received_message= '. Join (Self.received_data)

If Received_message==self.message:

Self.logger.debug (' RECEIVED COPY of MESSAGE ')

Else

Self.logger.debug (' ERROR in ')

Self.logger.debug ('%s '% (self.message))

Self.logger.debug ('%s ', received_message)

Return

    def writable (self): # Span style= "Font-family:tahoma;" >readable () ,poll () or select () asynoce code processing,  You do not need to use asynoce implementation, This program only needs to indicate whether the dispatcher wants to read or write data, and in this client, as long as there is data sent to the server, writeable () returns true,readable () just Span style= "Font-family:tahoma;" >true

Self.logger.debug ('%s '%bool (self.to_send))

return bool (self.to_send)

def readable (self):

Self.logger.debug (' True ')

Return True

# Each time the loop is processed, if writable () makes a positive response, it calls handle_write(),echoclients divides a message into parts based on a given size limit to show how a fairly large multipart message is transferred by looping through multiple iterations, each time handle_write ()is called, will write the next part of the message until the message is fully utilized.

def handle_write (self):

Sent=self.send (Self.to_send[:self.chunk_size])

Self.logger.debug ('%d%r '% (Sent,self.to_send[:sent]))

Self.to_send=self.to_send[sent:]

# A similar readable () responds, call handle_read ()

def handle_read (self):

SENT=SELF.RECV (Self.chunk_size)

Self.logger.debug ('%d%r '% (Len (sent), sent))

Self.received_data.append (Sent)

If __name__== ' __main ':

Logging.basicconfig (level=logging. debug,format= '% (name) -11s (message) s ',)

address= (' localhost ', 0)

SERVER=ECHOSERVR (Address)

Ip,port=server.address

Message=open (' Lorname.txt ', ' R '). Read ()

Logging.info (('%d '), Len (message))

Click=echoclient (Ip,port,message=message)

Asyncore.loop ()

Pythonasyncore asynchronous Io is learned by the Python standard library

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.