异步非阻塞

import socket
import select

def f1(response):
    pass
def f2(response):
    pass
def f3(response):
    pass
def f4(response):
    pass
inputs = []
connects = []

url_list = [
    ('www.baidu.com',f1),
    ('www.cnblogs.com',f2),
    ('www.qq.com',f3),
    ('www.bing.com',f4),
]

for url_func in url_list:
    sk = socket.socket()
    sk.setblocking(False)  #不会阻塞但是会报错
    setattr(sk,'callback_func',url_func[1]) 
    try:
        # 阻塞,非阻塞报错,捕捉错误
        sk.connect((url_func[0],80))
    except BlockingIOError as e:
        pass

    inputs.append(sk)
    connects.append(sk)

while True:
    # 通过fileno方法,检测socket是否已经发生变化。
    # wlist = [sk(cnblogs),sk(qq)],表示链接成功
    rlist,wlist,elist = select.select(inputs,connects,[],0.05)

    # 链接成功
    for item in wlist:
        item.sendall("GET / http1.1\r\nhost:%s\r\nk:v\r\n\r\n")
        connects.remove(item)
    # 获取响应内容,对其执行之前设置的callback_fun
    for item in rlist:
        data = item.recv(8096)
        inputs.remove(item)
        item.callback_func(data)

    if not inputs:
        break

封装后

import socket
import select

class Request(object):
    def __init__(self,sk,func,url):
        self.sk = sk
        self.func = func
        self.url = url
    def fileno(self):
        return self.sk.fileno()

url_list = [
    ('www.baidu.com',f1),
    ('www.cnblogs.com',f2),
    ('www.qq.com',f3),
    ('www.bing.com',f4),
]

inputs = []
connects = []
for item in url_list:

    sk = socket.socket()
    sk.setblocking(False)
    try:
        sk.connect((item[0],80))
    except:
        pass
    obj = Request(sk,item[1],item[0])
    inputs.append(obj)
    connects.append(obj)

while True:
    # 检测socket是否已经发生变化。
    # wlist = [sk(cnblogs),sk(qq)],表示链接成功
    rlist,wlist,elist = select.select(inputs,connects,[],0.05)

    # 链接成功
    for item in wlist:
        item.sk.sendall("GET / http1.1\r\nhost:%s\r\nk:v\r\n\r\n")
        connects.remove(item)
    # 响应内容
    for item in rlist:
        data = item.sk.recv(8096)
        inputs.remove(item)
        item.func(data)

    if not inputs:
        break

 

posted @ 2017-11-14 19:40  吃柚子的小白  阅读(129)  评论(0编辑  收藏  举报