1. 程式人生 > >python epoll實現異步socket

python epoll實現異步socket

add 給定 bsp pen 子進程 from lose urg nts

一、同步和異步:

在程序執行中,同步運行意味著等待調用的函數、線程、子進程等的返回結果後繼續處理;異步指不等待當下的返回結果,直接運行主進程下面的程序,等到有返回結果時,通知主進程處理。有點高效。

二、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)#參數均為非必填項

python epoll實現異步socket