The python concurrent programming (non-blocking IO model, I / O multiplexing, socketserver use)

9.16 non-blocking IO model

cpu occupancy rate is too high

Server:

from Socket Import *
 Import Time 
S = Socket () 
s.bind (( ' 127.0.0.1 ' , 8080 )) 
s.listen ( . 5 ) 
s.setblocking (False)     # so that the connection can not be received not accept blocking 

r_list = []
 the while True:
     the try : 
        Conn, addr = s.accept () 
        r_list.append (Conn) the except BlockingIOError:
         # the time.sleep (. 3) # Print ( 'could get back to the other living') # Print ( 'RLIST : ', len (r_list))
    
        
        
        for conn in r_list:
            try:
                data=conn.recv(1024)
                conn.send(data.upper())
            except BlockingIOError:
                continue

Client;

from socket import *
import os
client = socket()
client.connect(('127.0.0.1', 8080))
​
while True:
    data='%s say hello' %os.getpid()
    client.send(data.encode('utf-8'))
    res=client.recv(1024)
    print(res.decode('utf-8'))

9.17 I / O multiplexer

Server:

from Socket Import *
 Import SELECT 
S = Socket () 
s.bind (( ' 127.0.0.1 ' , 8080 )) 
s.listen ( . 5 ) 
s.setblocking (False)                         # so that the connection can not be received not accept blocking 
# Print ( S) 

r_list = [S,] 
w_list = [] 
w_data = {}
 the while True:
     Print ( ' detected r_list: ' , len (r_list))
     Print ( ' detected w_list:' , Len (w_list))       # rl is an is an object to establish a socket connection in r_list 
    rl is an, WL, XL = select.select (r_list, w_list, [],) # r_list = [Server, Conn] 
    # Print (' rl is an: ', len (rl is an)) = # rl is an [Conn,] 
    # Print (' WL: ', len (WL)) 
# received message for R & lt in rl is an: # R & lt Conn = IF R & lt == S: 
            Conn, addr = r.accept () 
            r_list.append (Conn) the else :
             the try : 
                Data = r.recv (1024 )
                 IF Not
    
        
          Data:
                    r.close()
                    r_list.remove(r)
                    continue
                # r.send(data.upper())
                w_list.append(r)
                w_data[r]=data.upper()
            except ConnectionResetError:
                r.close()
                r_list.remove(r)
                continue
    # 发消息
    for w in wl:
        w.send(w_data[w])
        w_list.remove(w)
        w_data.pop(w)
View Code

Client:

from socket import *
import os
client = socket()
client.connect(('127.0.0.1', 8080))
​
while True:
    data='%s say hello' %os.getpid()
    client.send(data.encode('utf-8'))
    res=client.recv(1024)
    print(res.decode('utf-8'))
View Code

9.18 socketserver use

9.181 based on the tcp socketserver

Server:

Import SocketServer
 # communications cycle 
class MytcpHandler (of SocketServer.BaseRequestHandler):
     DEF handle (Self):
         the while True:
             the try : 
                Data = self.request.recv (1024)   # maximum limit data 1024 received 
                IF  Not Data: BREAK   # for linux system 
                self.request.send (data.upper ())   # Note: a transceiver in bytes are 
            the except ConnectionResetError:
                 BREAK 
        self.request.close () 
IF  the __name__ == ' __main__':
    #连接循环
    server=socketserver.ThreadingTCPServer(('127.0.0.1',8080),MytcpHandler)
    server.serve_forever()
​
    print(server.server_address)
    print(server.RequestHandlerClass)
    print(server.socket)

Client:

import socket
client=socket.socket(socket.AF_INET,socket.SOCK_STREAM)
client.connect(('127.0.0.1',8080))
​
while True:
    msg=input('>>: ').strip()
    client.send(msg.encode('utf-8'))
    data=client.recv(1024)
    print(data.decode('utf-8'))
client.close()

9.182 based on the udp socketserver

Server:

Import SocketServer
 # communications cycle 
class MyUDPHandler (of SocketServer.BaseRequestHandler):
     DEF handle (Self):
         Print (self.request) # (b'13404 Hello ', <socket.socket FD = 460, = AddressFamily.AF_INET Family, 
        RES = Self .request [0] # type = SocketKind.SOCK_DGRAM, proto = 0, LADDR = ( '127.0.0.1', 8080)>) 
        Print ( ' client to the data: ' , RES) 
        
        self.request [ . 1 ]. the sendto (res.upper (), self.client_address) 
IF  the __name__ == ' __main__ ' :
     # coupling cycles
    server=socketserver.ThreadingUDPServer(('127.0.0.1',8080),MyUDPHandler)
    server.serve_forever()
View Code

Client:

import socket
import os
client=socket.socket(socket.AF_INET,socket.SOCK_DGRAM)
​
while True:
    msg='%s hello' %os.getpid()
    client.sendto(msg.encode('utf-8'),('127.0.0.1',8080))
​
    res,server_addr=client.recvfrom(1024)
    print(res)
View Code

Guess you like

Origin www.cnblogs.com/mylu/p/11266748.html