Files
tokio/examples/hello.rs
T

47 lines
1.2 KiB
Rust
Raw Normal View History

2016-11-22 12:35:30 -08:00
//! A small example of a server that accepts TCP connections and writes out
//! `Hello!` to them, afterwards closing the connection.
//!
//! You can test this out by running:
//!
//! cargo run --example hello
//!
//! and then in another terminal executing
//!
2017-09-11 08:07:38 -07:00
//! cargo run --example connect 127.0.0.1:8080
2016-11-22 12:35:30 -08:00
//!
//! You should see `Hello!` printed out and then the `nc` program will exit.
2017-02-05 17:06:57 -08:00
extern crate env_logger;
2016-09-09 00:10:54 -07:00
extern crate futures;
2017-10-24 16:30:16 -07:00
extern crate tokio;
2017-02-05 17:06:57 -08:00
extern crate tokio_io;
2016-11-22 12:35:30 -08:00
use std::env;
use std::net::SocketAddr;
2016-09-09 00:10:54 -07:00
use futures::stream::Stream;
2017-10-24 16:30:16 -07:00
use tokio::reactor::Core;
use tokio::net::TcpListener;
2016-09-09 00:10:54 -07:00
fn main() {
2016-11-22 12:35:30 -08:00
env_logger::init().unwrap();
let addr = env::args().nth(1).unwrap_or("127.0.0.1:8080".to_string());
let addr = addr.parse::<SocketAddr>().unwrap();
2016-09-09 00:10:54 -07:00
let mut core = Core::new().unwrap();
2016-11-22 12:35:30 -08:00
let listener = TcpListener::bind(&addr, &core.handle()).unwrap();
2016-09-09 00:10:54 -07:00
let addr = listener.local_addr().unwrap();
println!("Listening for connections on {}", addr);
let clients = listener.incoming();
let welcomes = clients.and_then(|(socket, _peer_addr)| {
2017-02-05 17:06:57 -08:00
tokio_io::io::write_all(socket, b"Hello!\n")
2016-09-09 00:10:54 -07:00
});
let server = welcomes.for_each(|(_socket, _welcome)| {
Ok(())
});
core.run(server).unwrap();
}