rust tokio && mio
Mio
Mio是一个快速,低level的Rust库,旨在non-blocking APIs and event notifications。
Poll监视系统传输过来的events并封装为Event然后分发给所有注册了的处理器。
// `Poll` allows for polling of readiness events.
let poll = Poll::new()?;
// `Events` is collection of readiness `Event`s and can be filled by
// calling `Poll::poll`.
let events = Events::with_capacity(128);
在实现了Poll实例之后,还需要给Poll注册事件源(event source, a source of events which can be polled using a Poll instance)让其监视。
// Create a `TcpListener`, binding it to `address`.
let mut listener = TcpListener::bind(address)?;
// Next we register it with `Poll` to receive events for it. The `SERVER`
// `Token` is used to determine that we received an event for the listener
// later on.
const SERVER: Token = Token(0);
poll.registry().register(&mut listener, SERVER, Interest::READABLE)?;
在注册了事件源之后,就可以凭此监视时间发生。这里注意我们是使用token来监视到底发生了什么事件的。
// Start our event loop.
loop {
// Poll the OS for events, waiting at most 100 milliseconds.
poll.poll(&mut events, Some(Duration::from_millis(100)))?;
// Process each event.
for event in events.iter() {
// We can use the token we previously provided to `register` to
// determine for which type the event is.
match event.token() {
SERVER => loop {
// One or more connections are ready, so we'll attempt to
// accept them (in a loop).
match listener.accept() {
Ok((connection, address)) => {
println!("Got a connection from: {}", address);
},
// A "would block error" is returned if the operation
// is not ready, so we'll stop trying to accept
// connections.
Err(ref err) if would_block(err) => break,
Err(err) => return Err(err),
}
}
}
}
}
fn would_block(err: &io::Error) -> bool {
err.kind() == io::ErrorKind::WouldBlock
}
Registry
use mio::{Events, Poll, Interest, Token};
use mio::net::TcpStream;
use std::net::SocketAddr;
use std::time::Duration;
let mut poll = Poll::new()?;
let address: SocketAddr = "127.0.0.1:0".parse()?;
let listener = net::TcpListener::bind(address)?;
let mut socket = TcpStream::connect(listener.local_addr()?)?;
// Register the socket with `poll`
poll.registry().register(
&mut socket,
Token(0),
Interest::READABLE)?;
poll.registry().deregister(&mut socket)?;
let mut events = Events::with_capacity(1024);
// Set a timeout because this poll should never receive any events.
poll.poll(&mut events, Some(Duration::from_secs(1)))?;
assert!(events.is_empty());
Tokio 0.3.6 PollEvented
Associates an I/O resource that implements the std::io::Read
and/or
std::io::Write
traits with the reactor that drives it.
PollEvented
uses Registration
internally to take a type that
implements mio::Evented
as well as std::io::Read
and or
std::io::Write
and associate it with a reactor that will drive it.
Once the mio::Evented
type is wrapped by PollEvented
, it can be
used from within the future's execution model. As such, the
PollEvented
type provides AsyncRead
and AsyncWrite
implementations using the underlying I/O resource as well as readiness
events provided by the reactor.
Note: While PollEvented
is Sync
(if the underlying I/O type is
Sync
), the caller must ensure that there are at most two tasks that
use a PollEvented
instance concurrently. One for reading and one for
writing. While violating this requirement is "safe" from a Rust memory
model point of view, it will result in unexpected behavior in the form
of lost notifications and tasks hanging.
Readiness events
Besides just providing AsyncRead
and AsyncWrite
implementations,
this type also supports access to the underlying readiness event stream.
While similar in function to what Registration
provides, the
semantics are a bit different.
Two functions are provided to access the readiness events:
poll_read_ready
and poll_write_ready
. These functions return the
current readiness state of the PollEvented
instance. If
poll_read_ready
indicates read readiness, immediately calling
poll_read_ready
again will also indicate read readiness.
When the operation is attempted and is unable to succeed due to the I/O
resource not being ready, the caller must call clear_read_ready
or
clear_write_ready
. This clears the readiness state until a new
readiness event is received.
This allows the caller to implement additional functions. For example,
TcpListener
implements poll_accept by using poll_read_ready
and
clear_read_ready
.
Platform-specific events
PollEvented
also allows receiving platform-specific mio::Ready
events.
These events are included as part of the read readiness event stream. The
write readiness event stream is only for Ready::writable()
events.
【推荐】编程新体验,更懂你的AI,立即体验豆包MarsCode编程助手
【推荐】凌霞软件回馈社区,博客园 & 1Panel & Halo 联合会员上线
【推荐】抖音旗下AI助手豆包,你的智能百科全书,全免费不限次数
【推荐】博客园社区专享云产品让利特惠,阿里云新客6.5折上折
【推荐】轻量又高性能的 SSH 工具 IShell:AI 加持,快人一步
· DeepSeek 解答了困扰我五年的技术问题
· 为什么说在企业级应用开发中,后端往往是效率杀手?
· 用 C# 插值字符串处理器写一个 sscanf
· Java 中堆内存和栈内存上的数据分布和特点
· 开发中对象命名的一点思考
· 为什么说在企业级应用开发中,后端往往是效率杀手?
· DeepSeek 解答了困扰我五年的技术问题。时代确实变了!
· 本地部署DeepSeek后,没有好看的交互界面怎么行!
· 趁着过年的时候手搓了一个低代码框架
· 推荐一个DeepSeek 大模型的免费 API 项目!兼容OpenAI接口!