文章目录
网络IO模型比较常见的是阻塞IO模型,非阻塞IO模型, IO多路复用,异步IO模型
- 阻塞IO模型 blocking IO
网络中阻塞包括:accept, recv, recvfrom
非阻塞: setblocking(False) (遇到阻塞就报错)
在recv阻塞过程中,操作系统做了哪些事情
- 非阻塞IO模型 nonblocking IOD
代码实现
server
import socket
sk = socket.socket()
sk.bind(('127.0.0.1', 9090))
sk.setblocking(False)
sk.listen()
conn_l =[]
del_l = []
while True:
try:
conn, addr = sk.accept()
conn_l.append(conn)
except BlockingIOError:
for conn in conn_l:
try:
conn.send(b'hello')
print(conn.recv(1024))
print('123')
except (NameError, BlockingIOError):
pass
except ConnectionResetError:
conn.close()
del_l.append(conn)
for del_conn in del_l:
conn_l.remove(del_conn)
del_l.clear()
client
import socket
sk = socket.socket()
sk.connect(('127.0.0.1', 9090))
for i in range(100000):
print(sk.recv(1024))
sk.send(b'world')
sk.close()
- IO多路复用 IO multiplexing
server
import socket
import select
sk = socket.socket()
sk.bind(('127.0.0.1', 9090))
sk.setblocking(False)
sk.listen()
r_lst = [sk, ]
while True:
r_l, _, _ = select.select(r_lst, [], [])
for item in r_l:
if item is sk:
conn, addr = sk.accept()
r_lst.append(conn)
else:
try:
print(item.recv(1024))
item.send(b'hello')
except ConnectionResetError:
item.close()
r_lst.remove(item)
client
import socket
sk = socket.socket()
sk.connect(('127.0.0.1', 9090))
for i in range(100000):
sk.send(b'world')
print(sk.recv(1024))
sk.close()
- 异步IO模型 asychronous IO