cargo.toml
[dependencies]
mio = {version = "1.0.2", features = ["os-poll", "net"]}
use std::io;
use mio::net::TcpListener;
TcpListener from the mio library, which will be used to listen for incoming TCP connections.use mio::{Events, Interest, Poll, Token};
Import necessary types from mio: Events for event handling,
Interest for specifying event types, Poll for polling events,
and Token for identifying event sources.
fn main() -> io::Result<()> {
io::Result to handle potential I/O errors. let mut poll = Poll::new()?;
Create a new Poll instance.
This allows us to monitor multiple event sources like network sockets.
The ‘?’ operator handles errors, returning them if they occur.
let mut events = Events::with_capacity(1024);
Events object with a capacity of 1024.let addr = "127.0.0.1:8080".parse().unwrap();
SocketAddr.unwrap() is used to handle potential parsing errors, though it will panic if there’s an error. let mut server = TcpListener::bind(addr)?;
TcpListener to the specified address.TcpListener with the Poll instance.Token(0) to identify it later,READABLE events
poll.registry().register(&mut server, Token(0), Interest::READABLE)?;
loop {
poll.poll(&mut events, None)?;
None’ argument means there’s no timeout,
events’ object. for event in events.iter() {
match event.token() {
Token(0) => {
Token(0), this means the event is from theTcpListener (i.e., a new connection is ready to be accepted).
let (_socket, address) = server.accept()?;
_socket’ is the TcpStream for the connection,address’ is the client’s address.TcpStream is not used further in this example. println!("Accepted connection from: {:?}", address);
}
_ => unreachable!(),
Token(0), this should never be reached. If it is, the program will panic. }
}
}
}