IO多路复用与异步非阻塞
1.基于socket,发送http请求
import socket import requests # 方式一 list=['li','gh ','nn'] for i in list: ret=requests.get('https://www.baidu.com/s?wd=%s' % i) # 方式二 def func(key): client=socket.socket() client.connect(('www.baidu.com',80)) client.sendall(b'GET /s?wd=alex HTTP/1.0\r\nhost:www.baidu.com\r\n\r\n') #http协议 chunk_list=[] while True: chuck=client.recv(8096) if not chuck: break chunk_list.append(chuck) body=b''.join(chunk_list) print(body.decode('utf-8')) list=['li','gh ','nn'] for key in list: func(key)
单线程的并发:IO多路复用,非阻塞
import socket import requests # 方式一 list=['li','gh ','nn'] for i in list: ret=requests.get('https://www.baidu.com/s?wd=%s' % i) # 方式二 def func(key): client=socket.socket() client.connect(('www.baidu.com',80)) client.sendall(b'GET /s?wd=alex HTTP/1.0\r\nhost:www.baidu.com\r\n\r\n') #http协议 chunk_list=[] while True: chuck=client.recv(8096) if not chuck: break chunk_list.append(chuck) body=b''.join(chunk_list) print(body.decode('utf-8')) list=['li','gh ','nn'] for key in list: func(key)
Twised基于事件循环实现的异步非阻塞
socket_list=[Foo(client1),Foo(client2),Foo(client3)] conn_list=[client1,client2,client3] err_list=[] while True: # 方式一: #没有执行自己的fileno方法 # rlist,wlist,elist=select.select(socket_list,conn_list,[],0.005)#这里面的socket_list/conn_list内部会调用每一个值的fileno方法,获得返回值 # 方式二: # select就是利用该返回值去判检测的 # rlist, wlist, elist = select.select([Foo(client1),Foo(client2),Foo(client3)], [client1,client2,client3], [], 0.005) if wlist: #执行类中的fileno方法
改变世界,改变自己!