python-IO多路复用的selectors模块

Posted benchdog

tags:

篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了python-IO多路复用的selectors模块相关的知识,希望对你有一定的参考价值。

server端:

import selectors
import socket

sel = selectors.DefaultSelector()

def accept(sock, mask):
    conn, addr = sock.accept()  # Should be ready
    print(accepted, conn, from, addr)
    conn.setblocking(False)
    sel.register(conn, selectors.EVENT_READ, read)

def read(conn, mask):
    try:
        data = conn.recv(1000)  # Should be ready
        if not data:
            raise Exception
        print(echoing, repr(data), to, conn)
        conn.send(data)  # Hope it won‘t block
    except Exception as e:
        print(closing, conn)
        sel.unregister(conn)
        conn.close()

sock = socket.socket()
sock.bind((localhost, 8090))
sock.listen(100)
sock.setblocking(False)

sel.register(sock, selectors.EVENT_READ, accept)
print("server.....")

while True:
    events = sel.select()#[sock,,conn2]
    for key, mask in events:
        callback = key.data
        callback(key.fileobj, mask)

client端:

# import socket
#
# sk=socket.socket()
#
# sk.connect(("127.0.0.1",8090))
# while 1:
#     inp=input(">>>")
#     sk.send(inp.encode("utf8"))
#     data=sk.recv(1024)
#     print(data.decode("utf8"))

 

以上是关于python-IO多路复用的selectors模块的主要内容,如果未能解决你的问题,请参考以下文章

Python-IO多路复用

python-IO多路复用之epoll

IO多路复用_selectors模块_python

Python3标准库:selectors I/O多路复用抽象

selecter模块默认使用epoll 实现IO多路复用,展示单线程的并发效果

Day15 - Python基础15 模块学习-selectors