Python - IO module select the multiplexing method poll

Python - IO module select the multiplexing method poll

IO multiplexing method implemented using poll

.
├── poll_client.py
├── poll_server.py
└── settings.py

 

# settings.py

HOST = 'localhost'
PORT = 5555
buffersize = 1024
ADDR = HOST, PORT

 

# Poll_server.py 

from Settings Import *
 from SELECT Import *
 from Socket Import * 

S = Socket () 
s.setsockopt (SOL_SOCKET, the SO_REUSEADDR, . 1)   # Set the port immediately reusable 
s.bind (ADDR) 
s.listen () 

# Create Object poll 
the p-= poll () 

# create a map (dictionary) 
fdmap = {s.fileno (): S} 

# Register attention (event) 
p.register (S, POLLIN | POLLERR)
 # POLLIN the corresponding parameter rlist select method - > IO events waiting to be processed 
#POLLOUT wlist select the corresponding parameters of the process -> active IO processing event 
# parameters xlist select a method corresponding to the POLLERR -> IO error handling event 

the while True:
     # of IO monitoring 
    # Events = [(the fileno, Event), .. .] 
    the try : 
        Events = p.poll ()
     the except KeyboardInterrupt:
         Print ( ' KeyboardInterrupt: Ctrl + C to Exit ' )
         BREAK 

    for fd, Event in Events:
         IF fd == s.fileno ():
             # find fd from the map corresponding object 
            Conn, addr = fdmap [FD] .accept ()
            Print ( ' Connect from ' , addr)
             # registered concern 
            p.register (conn, POLLIN)
             # add to the map 
            fdmap [conn.fileno ()] = conn
         the else : 
            the Data = fdmap [fd] .recv (buffersize)
             IF  not the Data: 
                p.unregister (fd)   # cancel the registration 
                fdmap [fd] .close ()   # close the socket 
                del fdmap [fd]   # deleted from the map in 
            the else :
                 Print (fdmap [fd] .getpeername (), data.decode ()) 
                fdmap [fd] .send (b'Roger that!')
s.close()
print('El Fin')        

 

# client.py

from socket import *
from settings import *

s = socket()
s.connect(ADDR)

while True:
    data = input('>> ')
    if not data:
        break
    s.send(data.encode())
    print(s.recv(buffersize).decode())

s.close()

 

Guess you like

Origin www.cnblogs.com/noonjuan/p/11281767.html