use log::warn;
use mio::net::UdpSocket;
use mio::{Events, Interest, Poll, Token};
use std::io;
const UDP_SOCKET: Token = Token(0);
fn main() -> io::Result<()> {
env_logger::init();
let mut poll = Poll::new()?;
let mut events = Events::with_capacity(1);
let addr = "127.0.0.1:9000".parse().unwrap();
let mut socket = UdpSocket::bind(addr)?;
poll.registry()
.register(&mut socket, UDP_SOCKET, Interest::READABLE)?;
println!("You can connect to the server using `nc`:");
println!(" $ nc -u 127.0.0.1 9000");
println!("Anything you type will be echoed back to you.");
let mut buf = [0; 1 << 16];
loop {
poll.poll(&mut events, None)?;
for event in events.iter() {
match event.token() {
UDP_SOCKET => loop {
match socket.recv_from(&mut buf) {
Ok((packet_size, source_address)) => {
socket.send_to(&buf[..packet_size], source_address)?;
}
Err(e) if e.kind() == io::ErrorKind::WouldBlock => {
break;
}
Err(e) => {
return Err(e);
}
}
},
_ => {
warn!("Got event for unexpected token: {:?}", event);
}
}
}
}
}