select源码涉及到操作系统级别的网络编程,这里给出一个简单的Python示例,使用select模块实现I/O多路复用。
import select import socket import sys server = socket.socket(socket.AF_INET, socket.SOCK_STREAM) server.setblocking(False) server_address = ('localhost', 10000) print('starting up on {} port {}'.format(*server_address)) server.bind(server_address) server.listen(5) inputs = [server] outputs = [] message_queues = {} while inputs: print('waiting for the next event') readable, writable, exceptional = select.select(inputs, outputs, inputs) for s in readable: if s is server: connection, client_address = s.accept() print('new connection from', client_address) connection.setblocking(0) inputs.append(connection) message_queues[connection] = [] else: data = s.recv(1024) if data: print('received "{}" from {}'.format(data, s.getpeername())) message_queues[s].append(data) if s not in outputs: outputs.append(s) else: print('closing', client_address) if s in outputs: outputs.remove(s) inputs.remove(s) s.close() del message_queues[s] for s in writable: if message_queues[s]: next_msg = message_queues[s].pop(0) print('sending "{}" to {}'.format(next_msg, s.getpeername())) s.send(next_msg) else: outputs.remove(s) for s in exceptional: print('handling exceptional condition for', s.getpeername()) inputs.remove(s) if s in outputs: outputs.remove(s) s.close() del message_queues[s]
这个示例中,我们创建了一个简单的TCP服务器,使用select模块来处理多个客户端连接,当有新的连接到来时,我们将连接添加到输入列表中;当有数据可读时,我们从连接中读取数据并将其添加到消息队列中;当输出列表中有连接时,我们从消息队列中取出数据并发送给客户端,我们还处理了一些异常情况,如客户端断开连接等。
原创文章,作者:未希,如若转载,请注明出处:https://www.kdun.com/ask/1072734.html
本网站发布或转载的文章及图片均来自网络,其原创性以及文中表达的观点和判断不代表本网站。如有问题,请联系客服处理。
发表回复