Python——IO多路复用之select模块select方法
使用select模块的select方法实现Python——IO多路复用
实现同时将终端输入的文本以及客户端传输的文本写入文本文件中:
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, SO_REUSEADDR, 1) s.bind(ADDR) s.listen() rlist = [s, sys.stdin] # 需要等待处理的IO事件 wlist = [] # 希望主动处理的IO事件 xlist = [] # 出错后要处理的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] == ' ': f.write(' ') 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()
实现: