Files
tokio/examples/chat.rs
T

140 lines
5.3 KiB
Rust
Raw Normal View History

2016-09-23 02:14:03 +02:00
//! A chat server that broadcasts a message to all connections.
2016-10-13 11:36:32 -07:00
//!
//! This is a simple line-based server which accepts connections, reads lines
//! from those connections, and broadcasts the lines to all other connected
//! clients. In a sense this is a bit of a "poor man's chat server".
2016-11-22 12:35:30 -08:00
//!
//! You can test this out by running:
//!
//! cargo run --example chat
//!
//! And then in another window run:
//!
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 can run the second command in multiple windows and then chat between the
//! two, seeing the messages from the other client as they're received. For all
//! connected clients they'll all join the same room and see everyone else's
//! messages.
2016-09-23 02:14:03 +02: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-09-23 02:14:03 +02:00
use std::collections::HashMap;
use std::iter;
use std::env;
use std::io::{Error, ErrorKind, BufReader};
2017-10-25 10:54:54 -07:00
use std::sync::{Arc, Mutex};
2016-09-23 02:14:03 +02:00
2017-02-05 17:06:57 -08:00
use futures::Future;
2017-10-25 10:54:54 -07:00
use futures::future::Executor;
2017-02-05 17:06:57 -08:00
use futures::stream::{self, Stream};
2017-10-25 10:54:54 -07:00
use futures_cpupool::CpuPool;
2017-10-24 16:30:16 -07:00
use tokio::net::TcpListener;
use tokio::reactor::Core;
2017-02-05 17:06:57 -08:00
use tokio_io::io;
use tokio_io::AsyncRead;
2016-09-23 02:14:03 +02:00
fn main() {
let addr = env::args().nth(1).unwrap_or("127.0.0.1:8080".to_string());
let addr = addr.parse().unwrap();
2016-10-13 11:36:32 -07:00
// Create the event loop and TCP listener we'll accept connections on.
2016-09-23 02:14:03 +02:00
let mut core = Core::new().unwrap();
let handle = core.handle();
let socket = TcpListener::bind(&addr, &handle).unwrap();
println!("Listening on: {}", addr);
2017-10-25 10:54:54 -07:00
// This is currently a multi threaded server.
//
// Once the same thread executor lands, transition to single threaded.
let connections = Arc::new(Mutex::new(HashMap::new()));
2016-10-13 11:36:32 -07:00
let srv = socket.incoming().for_each(move |(stream, addr)| {
println!("New Connection: {}", addr);
2016-11-05 13:36:49 -07:00
let (reader, writer) = stream.split();
2016-09-23 02:14:03 +02:00
2016-10-14 23:03:46 +02:00
// Create a channel for our stream, which other sockets will use to
// send us messages. Then register our address with the stream to send
2016-10-13 11:36:32 -07:00
// data to us.
2016-11-18 15:20:39 -08:00
let (tx, rx) = futures::sync::mpsc::unbounded();
2017-10-25 10:54:54 -07:00
connections.lock().unwrap().insert(addr, tx);
2016-10-13 11:36:32 -07:00
// Define here what we do for the actual I/O. That is, read a bunch of
// lines from the socket and dispatch them while we also write any lines
// from other sockets.
let connections_inner = connections.clone();
2016-11-05 13:36:49 -07:00
let reader = BufReader::new(reader);
// Model the read portion of this socket by mapping an infinite
// iterator to each line off the socket. This "loop" is then
// terminated with an error once we hit EOF on the socket.
2017-08-24 08:16:04 -07:00
let iter = stream::iter_ok::<_, Error>(iter::repeat(()));
2016-11-05 13:36:49 -07:00
let socket_reader = iter.fold(reader, move |reader, _| {
// Read a line off the socket, failing if we're at EOF
let line = io::read_until(reader, b'\n', Vec::new());
let line = line.and_then(|(reader, vec)| {
if vec.len() == 0 {
Err(Error::new(ErrorKind::BrokenPipe, "broken pipe"))
} else {
Ok((reader, vec))
}
2016-09-23 02:14:03 +02:00
});
2016-11-05 13:36:49 -07:00
// Convert the bytes we read into a string, and then send that
// string to all other connected clients.
let line = line.map(|(reader, vec)| {
(reader, String::from_utf8(vec))
2016-09-23 02:14:03 +02:00
});
2016-11-05 13:36:49 -07:00
let connections = connections_inner.clone();
line.map(move |(reader, message)| {
println!("{}: {:?}", addr, message);
2017-10-25 10:54:54 -07:00
let mut conns = connections.lock().unwrap();
2016-11-05 13:36:49 -07:00
if let Ok(msg) = message {
// For each open connection except the sender, send the
// string via the channel.
2016-11-18 15:20:39 -08:00
let iter = conns.iter_mut()
2016-11-05 13:36:49 -07:00
.filter(|&(&k, _)| k != addr)
.map(|(_, v)| v);
for tx in iter {
2017-08-24 08:16:04 -07:00
tx.unbounded_send(format!("{}: {}", addr, msg)).unwrap();
2016-11-05 13:36:49 -07:00
}
} else {
2016-11-18 15:20:39 -08:00
let tx = conns.get_mut(&addr).unwrap();
2017-08-24 08:16:04 -07:00
tx.unbounded_send("You didn't send valid UTF-8.".to_string()).unwrap();
2016-11-05 13:36:49 -07:00
}
reader
})
});
2016-09-23 02:14:03 +02:00
2016-11-05 13:36:49 -07:00
// Whenever we receive a string on the Receiver, we write it to
// `WriteHalf<TcpStream>`.
let socket_writer = rx.fold(writer, |writer, msg| {
let amt = io::write_all(writer, msg.into_bytes());
let amt = amt.map(|(writer, _)| writer);
2016-11-18 15:20:39 -08:00
amt.map_err(|_| ())
2016-10-13 11:36:32 -07:00
});
2017-10-25 10:54:54 -07:00
let pool = CpuPool::new(1);
2016-10-14 23:03:46 +02:00
// Now that we've got futures representing each half of the socket, we
// use the `select` combinator to wait for either half to be done to
// tear down the other. Then we spawn off the result.
2016-10-13 11:36:32 -07:00
let connections = connections.clone();
2016-11-18 15:20:39 -08:00
let socket_reader = socket_reader.map_err(|_| ());
2016-11-05 13:36:49 -07:00
let connection = socket_reader.map(|_| ()).select(socket_writer.map(|_| ()));
2017-10-25 10:54:54 -07:00
pool.execute(connection.then(move |_| {
connections.lock().unwrap().remove(&addr);
2016-10-13 11:36:32 -07:00
println!("Connection {} closed.", addr);
Ok(())
2017-10-25 10:54:54 -07:00
})).unwrap();
2016-10-13 11:36:32 -07:00
2016-09-23 02:14:03 +02:00
Ok(())
});
2016-10-13 11:36:32 -07:00
// execute server
core.run(srv).unwrap();
2016-09-23 02:14:03 +02:00
}