1 //! A small server that writes as many nul bytes on all connections it receives.
2 //!
3 //! There is no concurrency in this server, only one connection is written to at
4 //! a time. You can use this as a benchmark for the raw performance of writing
5 //! data to a socket by measuring how much data is being written on each
6 //! connection.
7 //!
8 //! Typically you'll want to run this example with:
9 //!
10 //!     cargo run --example sink --release
11 //!
12 //! And then you can connect to it via:
13 //!
14 //!     cargo run --example connect 127.0.0.1:8080 > /dev/null
15 //!
16 //! You should see your CPUs light up as data's being shove into the ether.
17 
18 extern crate env_logger;
19 extern crate futures;
20 extern crate tokio_core;
21 extern crate tokio_io;
22 
23 use std::env;
24 use std::iter;
25 use std::net::SocketAddr;
26 
27 use futures::Future;
28 use futures::stream::{self, Stream};
29 use tokio_io::IoFuture;
30 use tokio_core::net::{TcpListener, TcpStream};
31 use tokio_core::reactor::Core;
32 
main()33 fn main() {
34     env_logger::init().unwrap();
35     let addr = env::args().nth(1).unwrap_or("127.0.0.1:8080".to_string());
36     let addr = addr.parse::<SocketAddr>().unwrap();
37 
38     let mut core = Core::new().unwrap();
39     let handle = core.handle();
40     let socket = TcpListener::bind(&addr, &handle).unwrap();
41     println!("Listening on: {}", addr);
42     let server = socket.incoming().for_each(|(socket, addr)| {
43         println!("got a socket: {}", addr);
44         handle.spawn(write(socket).or_else(|_| Ok(())));
45         Ok(())
46     });
47     core.run(server).unwrap();
48 }
49 
write(socket: TcpStream) -> IoFuture<()>50 fn write(socket: TcpStream) -> IoFuture<()> {
51     static BUF: &'static [u8] = &[0; 64 * 1024];
52     let iter = iter::repeat(());
53     Box::new(stream::iter_ok(iter).fold(socket, |socket, ()| {
54         tokio_io::io::write_all(socket, BUF).map(|(socket, _)| socket)
55     }).map(|_| ()))
56 }
57