PythonStudy——epoll 模块实现异步IO模型

与select模块实现的IO模型对比

1.select,需要遍历socket列表,频繁的对等待队列进行添加移除操作,

2.数据到达后还需要给变量所有socket才能获知哪些socket有数据

两个操作消耗的时间随着要监控的socket的数量增加而大大增加,

处于效率考虑才规定了最大只能监视1024个socket

epoll要解决的问题

1.避免频繁的对等待队列进行操作

2.避免遍历所有socket

对于第一个问题

我们先看select的处理方式

while True:
    r_list,w_list,x_list = select.select(rlist,wlist,xlist,0.5)
  # 这里的0.5是指select每0.5秒轮询一次对应的套接字有没有准备好

每次处理完一次读写后,都需要将所用过冲重复一遍,包括移除进程,添加进程,默认就会将进程添加到等待队列,并阻塞住进程,然而等待队列的更新操作并不频繁,

所以对于第一个问题

epoll采取的方案是,将对等待队列维护阻塞进程这两个操作进行拆分!!!

相关代码如下

import socket,select
server = socket.socket()
server.bind(("127.0.0.1",1688))
server.listen(5)

#创建epoll事件对象,后续要监控的事件添加到其中
epoll = select.epoll()
#注册服务器监听fd到等待读事件集合
epoll.register(server.fileno(), select.EPOLLIN)

# 等待事件发生
while True:
  for sock,event in epoll.poll():
    pass
```

# 在epoll中register 与 unregister函数用于维护等待队列

# epoll.poll则用于阻塞进程

这样一来就避免了 每次处理都需要重新操作等待队列的问题

对于第二个问题

select中进程无法获知哪些socket是有数据的所以需要遍历

epol为了解决这个问题,在内核中维护了一个就绪列表,

1.创建epoll对象,epoll也会对应一个文件,由文件系统管理

2.执行register时,将epoll对象 添加到socket的等待队列中

3.数据到达后,CPU执行中断程序,将数据copy给socket

4.在epoll中,中断程序接下来会执行epoll对象中的回调函数,传入就绪的socket对象

5.将socket,添加到就绪列表中

6.唤醒epoll等待队列中的进程

进程唤醒后,由于存在就绪列表,所以不需要再遍历socket了,直接处理就绪列表即可

解决了这两个问题后,并发量得到大幅度提升,最大可同时维护上万级别的socket

epoll相关函数

import select 导入select模块

epoll = select.epoll() 创建一个epoll对象

epoll.register(文件句柄,事件类型) 注册要监控的文件句柄和事件

事件类型:

  select.EPOLLIN 可读事件

  select.EPOLLOUT 可写事件

  select.EPOLLERR 错误事件

  select.EPOLLHUP 客户端断开事件

  epoll.unregister(文件句柄) 销毁文件句柄

  epoll.poll(timeout) 当文件句柄发生变化,则会以列表的形式主动报告给用户进程

  timeout为超时时间,默认为-1,即一直等待直到文件句柄发生变化,如果指定为1,那么epoll每1秒汇报一次当前文件句柄的变化情况,如果无变化则返回空

  epoll.fileno() 返回epoll的控制文件描述符(Return the epoll control file descriptor)

  epoll.modfiy(fineno,event) fineno为文件描述符 event为事件类型 作用是修改文件描述符所对应的事件

  epoll.fromfd(fileno) 从1个指定的文件描述符创建1个epoll对象

  epoll.close() 关闭epoll对象的控制文件描述符

案例

客户端代码

#coding:utf-8
#客户端
#创建客户端socket对象
import socket
clientsocket=socket.socket(socket.AF_INET,
socket.SOCK_STREAM)
#服务端IP地址和端口号元组
server_address = ('127.0.0.1',1688)
#客户端连接指定的IP地址和端口号
clientsocket.connect(server_address)

while True:
#输入数据
    data = raw_input('please input:')
    if data == "q":
        break
    if not data:
        continue
    #客户端发送数据
    clientsocket.send(data.encode("utf-8"))
    #客户端接收数据
    server_data = clientsocket.recv(1024)
    print ('客户端收到的数据:',server_data)
    #关闭客户端socket
clientsocket.close()
        

服务器代码

# coding:utf-8
import socket, select

server = socket.socket()
server.bind(("127.0.0.1", 1688))
server.listen(5)

msgs = []


fd_socket = {server.fileno(): server}
epoll = select.epoll()
# 注册服务器的 写就绪
epoll.register(server.fileno(), select.EPOLLIN)

while True:
    for fd, event in epoll.poll():
        sock = fd_socket[fd]
        print(fd, event)
        # 返回的是文件描述符 需要获取对应socket
        if sock == server:  # 如果是服务器 就接受请求
            client, addr = server.accept()
            # 注册客户端写就绪
            epoll.register(client.fileno(), select.EPOLLIN)
            # 添加对应关系
            fd_socket[client.fileno()] = client

        # 读就绪
        elif event == select.EPOLLIN:
            data = sock.recv(2018)
            if not data:
                # 注销事件
                epoll.unregister(fd)
                # 关闭socket
                sock.close()
                # 删除socket对应关系
                del fd_socket[fd]
                print(" somebody fuck out...")
                continue

            print(data.decode("utf-8"))
            # 读完数据 需要把数据发回去所以接下来更改为写就绪=事件
            epoll.modify(fd, select.EPOLLOUT)
            #记录数据
            msgs.append((sock,data.upper()))
        elif event == select.EPOLLOUT:
            for item in msgs[:]:
                if item[0] == sock:
                    sock.send(item[1])
                    msgs.remove(item)
            # 切换关注事件为写就绪
            epoll.modify(fd,select.EPOLLIN)
原文地址:https://www.cnblogs.com/tingguoguoyo/p/11005785.html