一、select方法
"""
IO多路复用(TCP结合IO多路复用实例代码,实现服务端代码收发)
"""
from socket import *
from select import select
HOST = "0.0.0.0"
PORT = 8888
ADDR = (HOST, PORT)
tcp_socket = socket()
tcp_socket.bind(ADDR)
tcp_socket.listen(5)
tcp_socket.setblocking(False)
rlist = [tcp_socket]
wlist = []
xlist = []
while True:
rs, ws, xs = select(rlist, wlist, xlist)
for r in rs:
if r is tcp_socket:
connfd, addr = r.accept()
print("Connect from", addr)
connfd.setblocking(False)
rlist.append(connfd)
else:
data = r.recv(1024)
if not data:
rlist.remove(r)
r.close()
continue
print(data.decode())
wlist.append(r)
for w in ws:
w.send(b"OK")
wlist.remove(w)
|