server.py
import socket import selectors sel = selectors.DefaultSelector() # 创建selectors对象,它会自动根据操作系统选择使用select,pool 还是epool def accept(sock, mask): conn, addr = sock.accept() print('accepted', conn, 'from', addr) conn.setblocking(False) sel.register(conn, selectors.EVENT_READ, read) def read(conn, mask):
try: data = conn.recv(1000) if not data:
raise Exception print('echoing', repr(data), 'to', conn) conn.send(data) except Exception as e: print('closing', conn) sel.unregister() conn.close() sock = socket.socket() sock.bind(('localhost', 8080)) sock.listen(100) sock.setblocking(False) sel.register(sock, selectors.EVENT_READ, accept) # 将sock对象跟accept做一个绑定,只要有sock对象有活动,就直接调用accept方法 while True: events = sel.select() # 使用selectors对象进行监听 for key, mask in events: # callback = key.data callback(key.fileobj, mask)
client.py
import socket sk = socket.socket(socket.AF_INET, socket.SOCK_STREAM) sk.connect(('localhost', 8080)) while True: inp = input('>>').strip() sk.sendall(inp.encode('utf-8')) data = sk.recv(1024) print(data.decode('utf-8'))