首页 > 代码库 > python的epoll及EPOLLLT

python的epoll及EPOLLLT

今天没事练习python的epoll,一开始写了个客户端:

#! /usr/pythonimport socket,sys,selectc=socket.socket(socket.AF_INET,socket.SOCK_STREAM)host = 127.0.0.1port=57777c.connect((host,port))epoll_fd = select.epoll()epoll_fd.register(c.fileno(),select.EPOLLIN)epoll_fd.register(sys.stdin.fileno(), select.EPOLLIN)str=""while True:    e_list = epoll_fd.poll()    for fd,events in e_list:      if fd == c.fileno() and events&select.EPOLLIN:        buf =  c.recv(1024)        if not len(buf):           break        print "ser:",buf      if fd == c.fileno() and events & select.EPOLLOUT:        #print ‘send msg to ser.‘        c.send(str)        epoll_fd.modify(c.fileno(), select.EPOLLIN)      if fd == sys.stdin.fileno() and events & select.EPOLLIN:        str="ssf"        epoll_fd.modify(c.fileno(), select.EPOLLOUT)c.close()

发现服务端总是进入死循环收信息,甚是迷惑。后来修改了 str="ssf"处,修改为raw_input,发现程序正常运行,恍然醒悟,epoll默认

是LT模式,缓冲里的数据没读走,是每次都会触发的,因此,上面的代码修改epoll_fd.register(sys.stdin.fileno(), select.EPOLLIN)

epoll_fd.register(sys.stdin.fileno(), select.EPOLLIN|select.EPOLLOUT) 也是能正常工作的。

附上最终代码:

client.py

 

#! /usr/pythonimport socket,sys,selectc=socket.socket(socket.AF_INET,socket.SOCK_STREAM)host = 127.0.0.1port=57777c.connect((host,port))epoll_fd = select.epoll()epoll_fd.register(c.fileno(),select.EPOLLIN)epoll_fd.register(sys.stdin.fileno(), select.EPOLLIN)str=""while True:    e_list = epoll_fd.poll()    for fd,events in e_list:      if fd == c.fileno() and events&select.EPOLLIN:        buf =  c.recv(1024)        if not len(buf):           break        print "ser:",buf      if fd == c.fileno() and events & select.EPOLLOUT:        #print ‘send msg to ser.‘        c.send(str)        epoll_fd.modify(c.fileno(), select.EPOLLIN)      if fd == sys.stdin.fileno() and events & select.EPOLLIN:        str=raw_input("me: ")        epoll_fd.modify(c.fileno(), select.EPOLLOUT)c.close()

 

简单的server和client相似

import socket, os,select,syshost=127.0.0.1port=57777s = socket.socket(socket.AF_INET,socket.SOCK_STREAM)s.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR, 1)s.bind((host,port))s.listen(10)epoll_obj=select.epoll()epoll_obj.register(sys.stdin.fileno(), select.EPOLLIN)print wait for connectcs,caddr=s.accept()epoll_obj.register(cs.fileno(), select.EPOLLIN)str=""while 1:    readylist = epoll_obj.poll()    for fd,event in readylist:        if fd == cs.fileno() and event & select.EPOLLIN:            buf = cs.recv(128)            if not len(buf):                cs.close()                break            print "cli: ", buf        if fd == cs.fileno() and event & select.EPOLLOUT:            cs.send(str)            epoll_obj.modify(cs.fileno(), select.EPOLLIN)        if fd == sys.stdin.fileno() and event&select.EPOLLIN:            str=raw_input("me:")            epoll_obj.modify(cs.fileno(), select.EPOLLOUT)

 

python的epoll及EPOLLLT