发布时间:2019-08-28 09:07:53编辑:auto阅读(1424)
#!/usr/bin/env python # -*- coding:utf-8 -*- # author: Changhua Gong import selectors import socket sel = selectors.DefaultSelector() '''selectors根据系统自动select或epoll''' def accept(sock, mask): conn, addr = sock.accept() # Should be ready print('accepted', conn, 'from', addr) conn.setblocking(False) # 设置连接不阻塞 sel.register(conn, selectors.EVENT_READ, read) # 新连接注册read回调函数 def read(conn, mask): data = conn.recv(1024) # Should be ready if data: print('echoing', repr(data), 'to', conn) conn.send(data) # Hope it won't block else: print('closing', conn) sel.unregister(conn) conn.close() sock = socket.socket() sock.bind(('localhost', 10000)) sock.listen(100) sock.setblocking(False) sel.register(sock, selectors.EVENT_READ, accept) # 注册sock,有连接进来则调用accept while True: events = sel.select() # 默认阻塞,有活动连接就返回活动的连接列表 for key, mask in events: callback = key.data # accept的内存地址或read的内存地址,即等于read或accept函数 callback(key.fileobj, mask) # 调用对应的回调函数,key.fileobj为文件句柄
上一篇: Python(1)
下一篇: python pip
47881
46450
37333
34773
29347
26008
24961
19979
19582
18075
5821°
6449°
5962°
5988°
7093°
5937°
5981°
6472°
6437°
7818°