Files
tokio/examples/sink.rs
T

62 lines
1.9 KiB
Rust
Raw Normal View History

2016-07-30 17:53:12 -07:00
//! A small server that writes as many nul bytes on all connections it receives.
//!
//! There is no concurrency in this server, only one connection is written to at
2016-11-22 12:35:30 -08:00
//! a time. You can use this as a benchmark for the raw performance of writing
//! data to a socket by measuring how much data is being written on each
//! connection.
//!
//! Typically you'll want to run this example with:
//!
//! cargo run --example sink --release
//!
//! And then you can connect to it via:
//!
2017-09-11 08:07:38 -07:00
//! cargo run --example connect 127.0.0.1:8080 > /dev/null
2016-11-22 12:35:30 -08:00
//!
//! You should see your CPUs light up as data's being shove into the ether.
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;
2017-10-25 10:54:54 -07:00
extern crate futures_cpupool;
2017-10-24 16:30:16 -07:00
extern crate tokio;
2017-02-05 17:06:57 -08:00
extern crate tokio_io;
2016-07-30 17:53:12 -07:00
use std::env;
2016-08-18 09:19:50 -07:00
use std::iter;
2016-07-30 17:53:12 -07:00
use std::net::SocketAddr;
use futures::Future;
2017-10-25 10:54:54 -07:00
use futures::future::Executor;
2016-08-18 09:19:50 -07:00
use futures::stream::{self, Stream};
2017-10-25 10:54:54 -07:00
use futures_cpupool::CpuPool;
2017-02-05 17:06:57 -08:00
use tokio_io::IoFuture;
2017-10-24 16:30:16 -07:00
use tokio::net::{TcpListener, TcpStream};
use tokio::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();
2017-10-25 10:54:54 -07:00
let pool = CpuPool::new(1);
2017-09-11 08:07:38 -07:00
let mut core = Core::new().unwrap();
let handle = core.handle();
let socket = TcpListener::bind(&addr, &handle).unwrap();
2017-01-24 20:52:48 -08:00
println!("Listening on: {}", addr);
2017-09-11 08:07:38 -07:00
let server = socket.incoming().for_each(|(socket, addr)| {
2016-09-07 16:11:19 -07:00
println!("got a socket: {}", addr);
2017-10-25 10:54:54 -07:00
pool.execute(write(socket).or_else(|_| Ok(()))).unwrap();
2016-09-07 16:11:19 -07:00
Ok(())
});
2017-09-11 08:07:38 -07:00
core.run(server).unwrap();
2016-07-30 17:53:12 -07:00
}
2016-09-02 11:07:52 -07:00
fn write(socket: TcpStream) -> IoFuture<()> {
2016-08-18 09:19:50 -07:00
static BUF: &'static [u8] = &[0; 64 * 1024];
2017-08-24 08:16:04 -07:00
let iter = iter::repeat(());
Box::new(stream::iter_ok(iter).fold(socket, |socket, ()| {
2017-02-05 17:06:57 -08:00
tokio_io::io::write_all(socket, BUF).map(|(socket, _)| socket)
2017-08-24 08:16:04 -07:00
}).map(|_| ()))
2016-07-30 17:53:12 -07:00
}