Files
tokio/examples/echo.rs
T

68 lines
1.9 KiB
Rust
Raw Normal View History

2016-07-30 17:53:12 -07:00
//! An echo server that just writes back everything that's written to it.
2016-11-02 16:57:27 -07:00
//!
//! If you're on unix you can test this out by in one terminal executing:
//!
//! ```sh
//! $ cargo run --example echo
//! ```
//!
//! and in another terminal you can run:
//!
//! ```sh
//! $ nc localhost 8080
//! ```
//!
//! Each line you type in to the `nc` terminal should be echo'd back to you!
2016-07-30 17:53:12 -07:00
2016-09-01 09:18:03 -07:00
extern crate env_logger;
2016-07-30 17:53:12 -07:00
extern crate futures;
2016-08-26 14:30:46 -07:00
extern crate tokio_core;
2016-07-30 17:53:12 -07:00
use std::env;
use std::net::SocketAddr;
use futures::Future;
use futures::stream::Stream;
2016-09-07 13:53:18 -07:00
use tokio_core::io::{copy, Io};
2016-09-02 11:07:52 -07:00
use tokio_core::net::TcpListener;
use tokio_core::reactor::Core;
2016-07-30 17:53:12 -07:00
fn main() {
2016-09-01 09:18:03 -07:00
env_logger::init().unwrap();
2016-07-30 17:53:12 -07:00
let addr = env::args().nth(1).unwrap_or("127.0.0.1:8080".to_string());
let addr = addr.parse::<SocketAddr>().unwrap();
// Create the event loop that will drive this server
2016-09-02 11:07:52 -07:00
let mut l = Core::new().unwrap();
2016-09-07 16:11:19 -07:00
let handle = l.handle();
2016-07-30 17:53:12 -07:00
// Create a TCP listener which will listen for incoming connections
let socket = TcpListener::bind(&addr, &handle).unwrap();
2016-09-07 16:11:19 -07:00
// Once we've got the TCP listener, inform that we have it
println!("Listening on: {}", addr);
// Pull out the stream of incoming connections and then for each new
// one spin up a new task copying data.
//
// We use the `io::copy` future to copy all data from the
// reading half onto the writing half.
let done = socket.incoming().for_each(move |(socket, addr)| {
let (reader, writer) = socket.split();
let amt = copy(reader, writer);
2016-09-07 16:11:19 -07:00
// Once all that is done we print out how much we wrote, and then
// critically we *spawn* this future which allows it to run
// concurrently with other connections.
let msg = amt.map(move |amt| {
println!("wrote {} bytes to {}", amt, addr)
}).map_err(|e| {
panic!("error: {}", e);
});
handle.spawn(msg);
Ok(())
2016-07-30 17:53:12 -07:00
});
l.run(done).unwrap();
}