zoukankan      html  css  js  c++  java
  • 异步非阻塞

    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
    host:%s
    k:v
    
    ")
            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
    host:%s
    k:v
    
    ")
            connects.remove(item)
        # 响应内容
        for item in rlist:
            data = item.sk.recv(8096)
            inputs.remove(item)
            item.func(data)
    
        if not inputs:
            break
  • 相关阅读:
    使用JQuery快速高效制作网页特效1章
    优化数据库设计
    sql语句
    java九章后的总结笔记
    C#总结
    数组。
    2018_学习资料备用
    03-11gR2单机通过RMAN恢复到RAC(未验证)
    02-oracle11g rac RMAN备份恢复至单机(未验证)
    01-spfile和pfile的区别,生成,加载和修复
  • 原文地址:https://www.cnblogs.com/c491873412/p/7834254.html
Copyright © 2011-2022 走看看