首页 > 代码库 > 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.1‘port=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.1‘port=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.1‘port=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 connect‘cs,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
声明:以上内容来自用户投稿及互联网公开渠道收集整理发布,本网站不拥有所有权,未作人工编辑处理,也不承担相关法律责任,若内容有误或涉及侵权可进行投诉: 投诉/举报 工作人员会在5个工作日内联系你,一经查实,本站将立刻删除涉嫌侵权内容。