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.