异步模式多客户端的例子。
server.py
import selectors import socket sel = selectors.DefaultSelector() 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) def read(conn, mask): try: data = conn.recv(1000) # Should be ready except: print('closing 1', conn) sel.unregister(conn) conn.close() else: if data: print('echoing', repr(data), 'to', conn) conn.send(data) # Hope it won't block else: print('closing 2', conn) sel.unregister(conn) conn.close() sock = socket.socket() sock.bind((socket.gethostname(), 12345)) sock.listen(100) sock.setblocking(False) sel.register(sock, selectors.EVENT_READ, accept) while True: ''' 第一次: 会阻塞在select()这里, 解除阻塞: 当客户端调用connect方法时,解除阻塞,此时callback是本代码中的accept方法, 执行完之后,又阻塞在select 第二次: 当客户端调用send发消息时, 解除阻塞, 此时callback是本代码中的read方法 ''' events = sel.select() for key, mask in events: callback = key.data callback(key.fileobj, mask)
client1.py
import socket import time s = socket.socket() host = socket.gethostname() port = 12345 s.connect((host, port)) for i in range(20): time.sleep(1) msg = str(i) s.send(msg.encode('utf8')) print(s.recv(1024).decode('utf8')) s.send('break'.encode('utf8')) s.close()
client2.py
import socket import time s = socket.socket() host = socket.gethostname() port = 12345 s.connect((host, port)) for i in range(20): time.sleep(1) msg = str(i) s.send(msg.encode('utf8')) print(s.recv(1024).decode('utf8')) s.send('break'.encode('utf8')) s.close()
版权声明:本文内容由互联网用户自发贡献,该文观点仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 举报,一经查实,本站将立刻删除。
如需转载请保留出处:https://bianchenghao.cn/bian-cheng-ji-chu/75.html