python epoll实现异步socket

一、同步和异步:

在程序执行中,同步运行意味着等待调用的函数、线程、子进程等的返回结果后继续处理;异步指不等待当下的返回结果,直接运行主进程下面的程序,等到有返回结果时,通知主进程处理。有点高效。

二、epoll实现异步网络通信:

首先epoll只支持linux下的python。

服务端实现epoll异步的主要流程就是如下代码,讲解将在代码里面书写:

 1 # -*- coding:utf -*-
 2 
 3 import socket
 4 import select
 5 '''
 6 需要用到的lib文件:
 7 socket、select
 8 '''
 9 if __name__ == "__main__":
10     server = socket.socket(socket.AF_INET,socket.SOCK_STREAM)
11     server.setsockopt(socket.SOL_SOCKET,socket.SO_REUSEADDR,1)#IP地址端口复用
12     ipaddress = "127.0.0.1"
13     port = 33445
14     address = (ipaddress,port)
15     serverfd = server.fileno()
16     server.bind(address)
17     serverdict = {}
18     serverdict[serverfd] = server
19     epoll = select.epoll()#创建epoll对象
20     epoll.register(serverfd,select.EPOLLIN)#注册消息类型(输入)
21     server.listen(5)
22     while True:
23         events = epoll.poll(1)#创建事件队列
24         for fileno,event in events:
25             if fileno == serverfd:
26                 (client,address) = socket.accept()
27                 print "<-----",client,"----",address,"----->"
28                 client.setblocking(0)
29                 epoll.register(client.fileno(),select.EPOLLIN)#注册事件队列
30                 serverdict[client.fileno()] = client
31             elif event & select.EPOLLIN:#当有事件时候处理
32                 print "client:",fileno
33                 data = serverdict[fileno].recv(4096)
34                 print data
35                 

核心步骤如下:

 1 #创建epoll
 2 epoll = select.epoll()
 3 #注册事件队列
 4 epoll.register(socketname.filefd,select.EPOLLIN)#EPOLLIN是事件类型
 5 #创建事件队列:
 6 events = epoll.poll(1)
 7 #事件队列的数据结构:
 8 #(文件对象描述符,事件消息)
 9 #检测事件 进行处理:
10 for (fd,event) in events:
11     if event & select.EPOLLIN:
12         do_somethings()
13 #常用事件类型:
14 '''
15 EPOLLIN    Available for read
16 EPOLLOUT    Available for write
17 EPOLLPRI    Urgent data for read
18 EPOLLERR    Error condition happened on the assoc. fd
19 EPOLLHUP    Hang up happened on the assoc. fd
20 EPOLLET    Set Edge Trigger behavior, the default is Level Trigger behavior
21 EPOLLONESHOT    Set one-shot behavior. After one event is pulled out, the fd is internally disabled
22 EPOLLRDNORM    Equivalent to EPOLLIN
23 EPOLLRDBAND    Priority data band can be read.
24 EPOLLWRNORM    Equivalent to EPOLLOUT
25 EPOLLWRBAND    Priority data may be written.
26 EPOLLMSG    Ignored.
27 '''

其他常用的函数:

1 epoll.close()
2 epoll.fileno()#返回epoll对象的文件描述符
3 epoll.fromfd(fd)#从给定对象创建一个epoll对象
4 epoll.modify(fd,eventmask)#修改文件文件描述对象的epoll事件类型
5 epoll.unregister(fd)取消注册
6 epoll.poll(timeout=xxx,maxevents=xxx)#参数均为非必填项
原文地址:https://www.cnblogs.com/KevinGeorge/p/8183519.html