Python - IO module select the select multiplexing method

Python - IO module select the select multiplexing method

Using select select module implemented method Python - IO multiplexer

Achieve simultaneously entered text, and the text terminal transmitted from the client to write a text file:

write_file/
├── client.py
├── server.py
├── settings.py
└── text

 

# settings.py

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

 

# Server.py 

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

S = Socket () 
s.setsockopt (SOL_SOCKET, the SO_REUSEADDR, . 1 ) 
s.bind (ADDR) 
s.listen () 

RLIST = [S, SYS .stdin]     # required IO events awaiting processing 
wlist = []         # desired active IO event processing 
XList = []         # after an error event to process IO 

F = Open ( ' text ' , ' W ', encoding='utf-8')

while True:
    print('Waiting for connection...')
    try:
        rs, ws, xs = select(rlist, wlist, xlist)    
    except KeyboardInterrupt:
        # 按下Ctrl+C退出程序
        print('KeyboardInterrupt: Ctrl+C to exit')
        break
    
    for r in rs:
        if r is s:
            conn, addr = s.accept()
            # 将客户端套接字加入监听列表
            rlist.append(conn)    
        elif r is sys.stdin:
            data = r.readline()
            f.write(data)
            f.flush()
        else:
            data = r.recv(buffersize)
            if not data:
                rlist.remove(r)
                r.close()
            else:
                data = data.decode()
                f.write(data)
                if not data[-1] == '\n':
                    f.write('\n')    
                f.flush()

f.close()
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())

s.close()

 

achieve:

Guess you like

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