[−][src]Module mio::guide
Getting started guide.
Using Mio starts by creating a Poll
instance, which reads events from
the OS and puts them into Events
.
// `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);
Next an event source needs to be registered with Poll
to receive
events for it. We'll use a TcpListener
for which we'll receive an event
once a connection is ready to be accepted.
// 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)?;
As the name “event source” suggests it is a source of events which can
be polled using a Poll
instance. Multiple event sources can be
registered with Poll
. After we've done this we can start polling
these events. If we do this in a loop we've got ourselves an event loop.
// Start our event loop. loop { // Poll Mio 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 }