Module guide
Getting started guide.
In this guide we'll do the following:
- Create a
Pollinstance (and learn what it is). - Register an event source.
- Create an event loop.
At the end you'll have a very small (but quick) TCP server that accepts connections and then drops (disconnects) them.
1. Creating a Poll instance
Using Mio starts by creating a Poll instance, which monitors events
from the OS and puts them into Events. This allows us to execute I/O
operations based on what operations are ready.
# use ;
#
For example if we're using a TcpListener, we'll only want to
attempt to accept an incoming connection iff any connections are
queued and ready to be accepted. We don't want to waste our time if no
connections are ready.
2. Registering event source
After we've created a Poll instance that monitors events from the OS
for us, we need to provide it with a source of events. This is done by
registering an event source. As the name “event source” suggests it is
a source of events which can be polled using a Poll instance. On Unix
systems this is usually a file descriptor, or a socket/handle on
Windows.
In the example below we'll use a TcpListener for which we'll receive
an event (from Poll) once a connection is ready to be accepted.
# use TcpListener;
# use ;
#
Multiple event sources can be registered (concurrently), so we can monitor multiple sources at a time.
3. Creating the event loop
After we've created a Poll instance and registered one or more
event sources with it, we can poll it for events. Polling for events
is simple, we need a container to store the events: Events and need
to do something based on the polled events (this part is up to you, we
can't do it all!). If we do this in a loop we've got ourselves an event
loop.
The example below shows the event loop in action, completing our small TCP server.
# use io;
# use Duration;
# use TcpListener;
# use ;
#