首页 > 代码库 > python3 IO模型

python3 IO模型

概念:同步IO,异步IO ,阻塞IO,非阻塞IO

五种IO模型:

  blocking IO(阻塞IO)-了解

  nonblocking IO(非阻塞IO)-了解

  IO multiplexing(IO多路复用)-熟悉

  signal driven IO(异步IO)-忽略

  asynchronous IO(信号驱动IO)-忽略

 

select模块实现IO多路复用(单线程实现并发

import socket
import select

sock = socket.socket()
sock.bind((127.0.0.1,8080))
sock.listen(5)

inp = [sock,]   # 监听的套接字对象的列表,连接后,添加conn

while True:
    r = select.select(inp,[],[])  # [sock,conn1,conn2,conn3]  做了sock.accept()的第一件事
    print(r,r[0])

    for obj in r[0]:
        if obj == sock:
            conn,addr = obj.accept(conn)

        else:
            data = obj.recv(1024)
            print(data.decode(utf8))
            resp = input(>>>)
            obj.send(resp.encode(utf8))

 

selectors模块实现(常用)

import selectors
import socket

sel = selectors.DefaultSelector()

sock = socket.socket()
sock.bind((127.0.0.1,8080))
sock.listen(5)
sock.setblocking(False)

def accept(sock,mask):
    conn,addr = sock.accept()
    sel.register(conn,selectors.EVENT_READ,read)

def read(conn,mask):
    data = conn.recv(1024)
    print(data.decode("utf8"))
    resp = input(">>>>>")
    conn.send(resp.encode("utf8"))

# 绑定套接字对象和函数
sel.register(sock,selectors.EVENT_READ,accept)  # 注册对象fileobj,event,data

while True:

    events = sel.select()    # 监听套接字对象
    print(events:,events)
    for key,mask in events:
        callback = key.data # accept或者read
        callback(key.fileobj,mask)  # key.fileobj,sock或者conn

 

python3 IO模型