selectors模块介绍
Posted 管控念头
tags:
篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了selectors模块介绍相关的知识,希望对你有一定的参考价值。
import selectors # python封装的一个IO多路复用的模块,会根据系统的不同而选择不同的方法(select/epoll/poll) from socket import * sel = selectors.DefaultSelector() # 首先DefaultSelector()实例化一个对象 def accept(sock, mask): \'\'\'当有连接请求时,sock发生了变化,执行此函数\'\'\' conn, addr = sock.accept() print(\'accepted:\', conn, \'from:\', addr) conn.setblocking(False) # 将conn设置为非阻塞状态 sel.register(conn, selectors.EVENT_READ, read) # 将conn添加进监听列表,conn和read(自己写的read方法)做了一个绑定 def read(conn, mask): \'\'\'当conn发生变化时,执行此函数\'\'\' try: data = conn.recv(1024) # 当客户端输入为空时,不知道怎么办(在这里做为空判断没有用)!没有监听到吗还是什么其它原因呢? if data: print(\'echoing:\', repr(data), \'to:\', conn) conn.send(data) else: print(\'输入完毕退出...\') sel.unregister(conn) # 将conn移出监听列表 conn.close() except Exception: print(\'closing:\', conn) sel.unregister(conn) # # 将conn移出监听列表 conn.close() sock = socket(AF_INET, SOCK_STREAM) sock.bind((\'127.0.0.1\', 8080)) sock.listen(10) sock.setblocking(False) # 设置为非阻塞状态 sel.register(sock, selectors.EVENT_READ, accept) # 先将sock添加进监听列表,sock和accept(自己写的accept方法)做了一个绑定 while True: events = sel.select() # select进行监听 print(\'events:\', events) # events: [(SelectorKey(fileobj=<socket.socket fd=460, family=AddressFamily.AF_INET, type=SocketKind.SOCK_STREAM, proto=0, laddr=(\'127.0.0.1\', 8080)>, fd=460, events=1, data=<function accept at 0x0000021117343040>), 1)] # events: [(SelectorKey(fileobj=<socket.socket fd=120, family=AddressFamily.AF_INET, type=SocketKind.SOCK_STREAM, proto=0, laddr=(\'127.0.0.1\', 8080), raddr=(\'127.0.0.1\', 60268)>, fd=120, events=1, data=<function read at 0x0000021117558E50>), 1)] for key, mask in events: # print(type(key)) # <class \'selectors.SelectorKey\'> print(\'key:\', key) # key: SelectorKey(fileobj=<socket.socket fd=460, family=AddressFamily.AF_INET, type=SocketKind.SOCK_STREAM, proto=0, laddr=(\'127.0.0.1\', 8080)>, fd=460, events=1, data=<function accept at 0x0000021117343040>) # key: SelectorKey(fileobj=<socket.socket fd=120, family=AddressFamily.AF_INET, type=SocketKind.SOCK_STREAM, proto=0, laddr=(\'127.0.0.1\', 8080), raddr=(\'127.0.0.1\', 60268)>, fd=120, events=1, data=<function read at 0x0000021117558E50>) print(\'mask:\', mask) # mask: 1 # mask: 1 callback = key.data # <function accept at 0x0000021117343040>/<function read at 0x0000021117558E50> callback(key.fileobj, mask) # key.fileobj:<socket.socket fd=460, family=AddressFamily.AF_INET, type=SocketKind.SOCK_STREAM, proto=0, laddr=(\'127.0.0.1\', 8080)> # key.fileobj:<socket.socket fd=120, family=AddressFamily.AF_INET, type=SocketKind.SOCK_STREAM, proto=0, laddr=(\'127.0.0.1\', 8080), raddr=(\'127.0.0.1\', 60268)> # 第一行为服务端的sock(socket对象),第二行为客户端连接的conn(客户端的socket对象)
from socket import * cl = socket(AF_INET, SOCK_STREAM) cl.connect((\'127.0.0.1\', 8080)) msg = input(\'输入:\') cl.sendall(msg.encode(\'utf-8\')) data = cl.recv(1024) print(data.decode(\'utf-8\'))
以上是关于selectors模块介绍的主要内容,如果未能解决你的问题,请参考以下文章