python IO非阻塞模型

server端

import socket
sk = socket.socket()
sk.bind(('127.0.0.1', 8010))
sk.setblocking(False)   #
sk.listen()
conn_l = []
del_conn = []
while True:
    try:
        conn, addr = sk.accept()    # 不阻塞,但是没人连我会报错
        print('建立连接了:', addr)
        conn_l.append(conn)
    except BlockingIOError:
        for con in conn_l:
            try:
                msg = con.recv(1024)  # 非阻塞,如果没有数据就报错
                if msg == b'':
                    del_conn.append(con)
                    continue
                print(msg)
                con.send(b'bye')
            except BlockingIOError:
                pass
        for con in del_conn:
            con.close()
            conn_l.remove(con)
        del_conn.clear()

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(1)
    print(sk.recv(1024))
    sk.close()


for i in range(2):
    threading.Thread(target=func).start()

 

上一篇:python网络编程干货


下一篇:sk_buff内核api函数记录