一. IO多路复用
IO多路复用作用:检测多个socket是否已经发生变化(是否已经连接成功/是否已经获取数据)(可读/可写)
二. 基于IO多路复用+socket实现并发请求(一个线程100个请求)
IO多路复用
socket非阻塞
基于事件循环实现的异步非阻塞框架:aaaa.py
非阻塞:不等待
异步:执行完某个任务后自动调用我给他的函数。
Python中开源 基于事件循环实现的异步非阻塞框架 Twisted
# aaaa.py import socket import select class Req(object): def __init__(self,sk,func): self.sock = sk self.func = func def fileno(self): return self.sock.fileno() class Nb(object): def __init__(self): self.conn_list = [] self.socket_list = [] def add(self,url,func): client = socket.socket() client.setblocking(False) # 非阻塞 try: client.connect((url, 80)) except BlockingIOError as e: pass obj = Req(client,func) self.conn_list.append(obj) self.socket_list.append(obj) def run(self): while True: rlist,wlist,elist = select.select(self.socket_list,self.conn_list,[],0.005) # wlist中表示已经连接成功的req对象 for sk in wlist: # 发生变换的req对象 sk.sock.sendall(b‘GET /s?wd=alex HTTP/1.0\r\nhost:www.baidu.com\r\n\r\n‘) self.conn_list.remove(sk) for sk in rlist: chunk_list = [] while True: try: chunk = sk.sock.recv(8096) if not chunk: break chunk_list.append(chunk) except BlockingIOError as e: break body = b‘‘.join(chunk_list) # print(body.decode(‘utf-8‘)) sk.func(body) sk.sock.close() self.socket_list.remove(sk) if not self.socket_list: break
原文地址:https://www.cnblogs.com/NachoLau/p/9642969.html
时间: 2024-11-08 10:51:03