Files
tokio/examples/echo-udp.rs
T

71 lines
1.8 KiB
Rust
Raw Normal View History

2016-11-01 22:44:25 -07:00
//! An UDP echo server that just sends back everything that it receives.
2016-11-02 16:57:27 -07:00
//!
2018-08-25 15:26:41 -04:00
//! If you're on Unix you can test this out by in one terminal executing:
2016-11-02 16:57:27 -07:00
//!
2016-11-22 12:35:30 -08:00
//! cargo run --example echo-udp
2016-11-02 16:57:27 -07:00
//!
//! and in another terminal you can run:
//!
2017-09-11 08:32:34 -07:00
//! cargo run --example connect -- --udp 127.0.0.1:8080
2016-11-02 16:57:27 -07:00
//!
//! Each line you type in to the `nc` terminal should be echo'd back to you!
2016-11-01 22:44:25 -07:00
#![warn(rust_2018_idioms)]
2016-11-01 22:44:25 -07:00
2019-07-25 16:47:31 -04:00
use std::error::Error;
2016-11-01 22:44:25 -07:00
use std::net::SocketAddr;
2019-02-21 11:56:15 -08:00
use std::{env, io};
2017-10-24 16:30:16 -07:00
use tokio::net::UdpSocket;
2016-11-01 22:44:25 -07:00
struct Server {
2016-11-02 16:57:27 -07:00
socket: UdpSocket,
buf: Vec<u8>,
to_send: Option<(usize, SocketAddr)>,
2016-11-01 22:44:25 -07:00
}
2019-07-09 20:21:12 +02:00
impl Server {
async fn run(self) -> Result<(), io::Error> {
let Server {
socket,
2019-07-09 20:21:12 +02:00
mut buf,
mut to_send,
} = self;
2016-11-01 22:44:25 -07:00
loop {
2016-11-02 16:57:27 -07:00
// First we check to see if there's a message we need to echo back.
// If so then we try to send it back to the original source, waiting
2017-03-07 11:39:51 +08:00
// until it's writable and we're able to do so.
2019-07-09 20:21:12 +02:00
if let Some((size, peer)) = to_send {
let amt = socket.send_to(&buf[..size], &peer).await?;
2016-11-02 16:57:27 -07:00
println!("Echoed {}/{} bytes to {}", amt, size, peer);
2016-11-01 22:44:25 -07:00
}
2016-11-02 16:57:27 -07:00
// If we're here then `to_send` is `None`, so we take a look for the
// next message we're going to echo back.
2019-07-09 20:21:12 +02:00
to_send = Some(socket.recv_from(&mut buf).await?);
2016-11-01 22:44:25 -07:00
}
}
}
2019-07-09 20:21:12 +02:00
#[tokio::main]
2019-07-25 16:47:31 -04:00
async fn main() -> Result<(), Box<dyn Error>> {
let addr = env::args()
.nth(1)
.unwrap_or_else(|| "127.0.0.1:8080".to_string());
2016-11-01 22:44:25 -07:00
let socket = UdpSocket::bind(&addr).await?;
2019-07-25 16:47:31 -04:00
println!("Listening on: {}", socket.local_addr()?);
2016-11-01 22:44:25 -07:00
let server = Server {
socket,
2016-11-02 16:57:27 -07:00
buf: vec![0; 1024],
to_send: None,
};
// This starts the server task.
2019-07-25 16:47:31 -04:00
server.run().await?;
Ok(())
2016-11-01 22:44:25 -07:00
}