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方法
相關文章
相關標籤/搜索