Python IO多路复用

IO多路复用

多个socket是否已经发生变化,(是否已经连接成功/是否已经获得数据)(可读/可写)

实现:

  1. IO多路复用
  2. 非阻塞

代码如下:

import socket
import select

client1 = socket.socket()
client1.setblocking(False) # 将原本链接阻塞,修改为非阻塞
# 百度创建链接,阻塞
try:
    client1.connect(('www.baidu.com',80))
except BlockingIOError:
    pass

client2 = socket.socket()
client2.setblocking(False) # 将原本链接阻塞,修改为不阻塞
# 百度创建链接,阻塞
try:
    client2.connect(('www.sogou.com',80))
except BlockingIOError:
    pass

client3 = socket.socket()
client3.setblocking(False) # 将原本链接阻塞,修改为不阻塞
# 百度创建链接,阻塞
try:
    client3.connect(('www.oldboyedu.com',80))
except BlockingIOError:
    pass

socket_list = [client1,client2,client3]
conn_list = [client1,client2,client3]

while True:
    rlist,wlist,elist = select.select(socket_list,conn_list,[],0.005)

    for sk in wlist:
        if sk == client1:
            sk.sendall(b'GET /s?wd=alex HTTP/1.0\r\nhost:www.baidu.com\r\n\r\n')
        elif sk == client2:
            sk.sendall(b'GET /web?query=alex HTTP/1.0\r\nhost:www.sogou.com\r\n\r\n')
        else:
            sk.sendall(b'GET /s?wd=alex HTTP/1.0\r\nhost:www.oldboyedu.com\r\n\r\n')
        conn_list.remove(sk)

    for sk in rlist:
        chunk_list = []
        while True:
            try:
                chunk = sk.recv(8096)
                if not chunk:
                    break
                chunk_list.append(chunk)
            except BlockingIOError:
               break

        boby = b''.join(chunk_list)
        print('------->',boby)
        sk.close()
        socket_list.remove(sk)

    if not socket_list:
        break
上一篇:实验1 8086汇编指令编码和调试


下一篇:openwrt中在软件包中定义PKG_INSTALL将会发生什么?