Python IO多路复用

匿名 (未验证) 提交于 2019-12-02 22:51:30

多个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
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!