socket编程的select poll和epoll这两种机制,本质区别在哪里?
Posted
tags:
篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了socket编程的select poll和epoll这两种机制,本质区别在哪里?相关的知识,希望对你有一定的参考价值。
如题,谢谢!
参考技术A 例如你在大学中读书,要等待一个朋友来访,而这个朋友只知道你在H号楼,但不知道你在哪一个房间(例如H号楼有200个寝室),select/poll()模型(也就是多路复用模型),比如你的同学来了,select/poll比较笨,她带着你朋友挨个房间进行查询谁是同学你,找到你后,说你的朋友来了,epoll是poll的改进,他相当于登记了每个宿舍住的人的姓名,你的朋友到了H栋楼的门口,epoll(管理员)会问他,你找谁,你的朋友把你的名字一说,管理员查到你的房间号后,直接把他带到你的房间,区别就是这样,希望能帮到你!select —— poll —— epoll
import socket,select s=socket.socket() s.setblocking(False) s.setsockopt(socket.SOL_SOCKET,socket.SO_REUSEADDR,1) s.bind((‘127.0.0.1‘,6666)) s.listen() rlist=[s,] wlist=[] erlist=[] while True: rs,ws,er=select.select(rlist,wlist,erlist) print(1) for i in rs: if i is s: con,add=s.accept() rlist.append(con) else: date=i.recv(1024) if not date: rlist.remove(i) print(date.decode()) i.send(date) for i in erlist: print(i)
import socket,select,time s=socket.socket() s.setsockopt(socket.SOL_SOCKET,socket.SO_REUSEADDR,1) s.bind((‘127.0.0.1‘,6666)) s.listen() poll=select.poll() poll_dic={s.fileno(): s,} poll.register(s, select.POLLIN | select.POLLERR) while True: try: events=poll.poll() for fd,event in events: print(fd,event) if fd == s.fileno(): con,add=s.accept() poll_dic[con.fileno()] = con poll.register(con,select.POLLIN | select.POLLERR) elif event == select.POLLIN: date = poll_dic[fd].recv(1024) print(date.decode()) if not date: print(‘进来了‘) poll.unregister(fd) poll_dic[fd].close() del poll_dic[fd] except: poll.unregister(s)
import socket,select s=socket.socket() s.setsockopt(socket.SOL_SOCKET,socket.SO_REUSEADDR,1) s.bind((‘127.0.0.1‘,6666)) s.listen() poll=select.poll() poll_dict={s.fileno():s} def a(fd): poll.unregister(fd) poll_dict[fd].close() del poll_dict[fd] def main(): poll.register(s,select.POLLIN | select.POLLERR) while True: p=poll.poll() for fd,event in p: if fd == s.fileno(): con, addr = s.accept() poll.register(con, select.POLLIN | select.POLLERR) poll_dict[con.fileno()]=con elif event == select.POLLIN: date=poll_dict[fd].recv(1024) if not date: a(fd) continue print(date.decode(),111) poll_dict[fd].send(date) elif event == select.POLLERR: a(fd) if __name__ == ‘__main__‘: main()
import socket,selectors s=socket.socket() s.setsockopt(socket.SOL_SOCKET,socket.SO_REUSEADDR,1) s.bind((‘127.0.0.1‘,6666)) s.listen() epoll=selectors.DefaultSelector() def accept_(s): con,addr=s.accept() epoll.register(con,selectors.EVENT_READ,recv_) def recv_(con): try: date=con.recv(1024) if not date: raise ‘‘ print(date.decode()) con.send(date) except: epoll.unregister(con) con.close() print(‘断开连接‘) def main(): epoll.register(s,selectors.EVENT_READ,accept_) while True: s_eoll=epoll.select() for key,event in s_eoll: ac=key.data #这是文件指针accept_ print(key,‘这是KEY‘) ac(key.fileobj) if __name__ == ‘__main__‘: main()
以上是关于socket编程的select poll和epoll这两种机制,本质区别在哪里?的主要内容,如果未能解决你的问题,请参考以下文章