python IO多路复用
基于select
作用:I/O多路复用是用于提升效率,单个进程可以同时监听多个网络连接IO。
server端
import select import socket sk = socket.socket() sk.bind(('127.0.0.1', 8010)) sk.setblocking(False) sk.listen() read_lst = [sk] # while True: # [sk,conn] # select提供监听 r_lst, w_lst, x_lst = select.select(read_lst, [], []) # print(read_lst) for i in r_lst: if i is sk: conn, addr = i.accept() read_lst.append(conn) else: ret = i.recv(1024) if ret == b'': i.close() read_lst.remove(i) continue print(ret) i.send(b'bye!')
client端
import time import socket import threading def func(): sk = socket.socket() sk.connect(('127.0.0.1', 8010)) sk.send(b'hello') time.sleep(3) print(sk.recv(1024)) sk.close() for i in range(5): threading.Thread(target=func).start()
主要作用:定制异步框架