IO multiplexing -EPOOL Details

principle

When reading data from the stream inside, this data could not down the stream, in order to avoid idle CPU, introduced agents: select, pool, and later introduced changes epool to monitor the occurrence of file handles, this agency more powerful, it can be observed simultaneously many stream I / O events, in his spare time, will the current thread blocked out, when one or more streams have I / O event, woke up from the blocking states, so our program will poll over all streams. IO using select only know of the incident, and a few really do not know what happened, the introduction of epool, it can tell us which flow (flow: is a file, sockets, pipe and other kernel objects can be IO operations) What happens in the IO event.

epool usage

import select import select module 

epoll = select.epoll () objects to create a epoll 

file handle and events epoll.register (file handle, event type) registered to monitor 

the type of event: 

  select.EPOLLIN readable event 
  select.EPOLLOUT can write event 
  select .EPOLLERR error event 
  select.EPOLLHUP client disconnection events 

epoll.unregister (file handle) destroyed the file handle 

epoll.poll (timeout) when a file handle changes will be in the form of a list of active reporting to the user process, timeout 

                     to timeout , defaults to -1, i.e., waits until the file handle changed, if designated as a 

                     so epoll report every 1 second change of the current file handle return null if no change 

epoll.fileno () returns the control file is described epoll character (the Return the epoll the Control File descriptor) 

epoll.modfiy (fineno, event) fineno file descriptors for the event type event descriptor is to modify the action event corresponding 

one from the specified file descriptor epoll.fromfd (fileno) Creating an epoll objects 

epoll.close () closed epoll file descriptor object control

  

Examples

# ! / Usr / bin / env Python 
# - * - Coding: UTF-8 - * - 

Import socket
 Import the SELECT
 Import Queue 

# Create a socket object 
serversocket = socket.socket (socket.AF_INET, socket.SOCK_STREAM)
 # Set the IP address multiplexing with 
serversocket.setsockopt (socket.SOL_SOCKET, socket.SO_REUSEADDR, 1 )
 # ip address and port number 
server_address = ( " 127.0.0.1 " , 8888 )
 # bind IP address 
ServerSocket.bind (server_address)
 # monitor, and set the maximum connection number 
serversocket.listen (10 )
 Print   " server started successfully, monitor IP:" , Server_address
 # server set non-blocking 
serversocket.setblocking (False)  
 # timeout 
timeout = 10 # create epoll event object, the follow-up to monitor the event to which the 
epoll = select.epoll ()
 # registration server listens to fd waiting to be read event set epoll.register (serversocket.fileno (), select.EPOLLIN)
 # save dictionary connection client message format} { 
message_queues = {}
 # file handle object corresponding to the dictionary, the format {handles: object} 
= fd_to_socket {serversocket.fileno (): ServerSocket,} the while True:
   Print " wait active connection ...... " # polling register set of events, the return value [(a file handle corresponding to the event), (. ..), ....] 
  Events = epoll.poll (timeout)
  



 
  IF  not Events:
      Print  " epoll timeout no active connection, re-polling ...... " 
     the Continue 
  Print  " there " , len (Events), " a new event, starts processing ...... " 
  
  for fd, event in Events: 
     socket = fd_to_socket [fd]
      # if the current activity socket server socket, indicate a new connection 
     IF socket == serversocket: 
            connection, address = ServerSocket.accept ()
             Print  " new connection: " , address
             # new connection socket is set to a non-blocking
            connection.setblocking (False)
             # Register a new connection to be read fd set of events 
            epoll.register (connection.fileno (), select.EPOLLIN)
             # save file handles, and the object of the new connection to the dictionary 
            fd_to_socket [connection.fileno ()] = connection
             # to key target for the new connection, the value stored in the queue, stored information for each connection 
            message_queues [connection] = Queue.Queue ()
      # close event 
     elif event & select.EPOLLHUP:
         Print  ' Client Close ' 
        # Log off the client in the epoll file handle 
        epoll.unregister (fd)
         # close the file handle client 
        fd_to_socket [fd] .close ()
        # Deleting closed client-related information in a dictionary 
        del fd_to_socket [FD]
      # readable event 
     elif Event & select.EPOLLIN:
         # receiving data 
        Data = socket.recv (1024 )
         IF Data:
            Print  " receive data: " , data, " client: " , socket.getpeername ()
            # the client data into the corresponding dictionary 
           message_queues [Socket] .put (data)
            # modify message read event set is connected to the write wait (i.e., the corresponding client after receiving the message, and then modify it and add fd write event collection) 
           epoll.modify (fd, select.EPOLLOUT)
      # can write event 
     elif event &select.EPOLLOUT:
         the try :
            # obtain the corresponding client information from the dictionary 
           msg = message_queues [socket] .get_nowait ()
         the except Queue.Empty:
            Print socket.getpeername (), " Queue empty " 
           # modified file handle to read events 
           epoll. the Modify (fd, select.EPOLLIN)
         the else :
            Print  " to send data: " , the data, " client: " , socket.getpeername ()
            # sending data 
           socket.send (msg) 

# cancellation of the server file handle in the epoll
epoll.unregister (serversocket.fileno ())
 # close the epoll 
epoll.close ()
 # close server Socket 
serversocket.close () 

server code
Server code
# ! / Usr / bin / env Python 
# - * - Coding: UTF-8 - * - 

Import socket 

# Create the client socket object 
ClientSocket = socket.socket (socket.AF_INET, socket.SOCK_STREAM)
 # server IP address and port number tuple 
the server_address = ( ' 127.0.0.1 ' , 8888 )
 # client connections specified IP address and port number 
clientsocket.connect (the server_address) 

the while True:
     # of input data 
    data = the raw_input ( ' Please iNPUT: ' )
     # client transmission data 
    clientsocket.sendall (data)
     # client receives the data
    = clientsocket.recv SERVER_DATA (1024 )
     Print  ' data received by the client: ' SERVER_DATA
     # closed client Socket 
    clientsocket.close () 

client code
Client code

This article reference links: https://www.cnblogs.com/maociping/p/5132583.html

 

Guess you like

Origin www.cnblogs.com/djfboai/p/11535471.html