2020-05-27 15:58:57 +00:00
|
|
|
//!run with
|
|
|
|
//! ```bash
|
2020-08-26 08:07:22 +00:00
|
|
|
//! RUST_BACKTRACE=1 cargo run --example chat -- --trace=info --port 15006
|
|
|
|
//! RUST_BACKTRACE=1 cargo run --example chat -- --trace=info --port 15006 --mode=client
|
2020-05-27 15:58:57 +00:00
|
|
|
//! ```
|
2022-04-02 21:29:22 +00:00
|
|
|
use clap::{Arg, Command};
|
2020-07-13 21:13:54 +00:00
|
|
|
use std::{sync::Arc, thread, time::Duration};
|
2021-01-15 13:04:32 +00:00
|
|
|
use tokio::{io, io::AsyncBufReadExt, runtime::Runtime, sync::RwLock};
|
2020-04-08 14:26:42 +00:00
|
|
|
use tracing::*;
|
|
|
|
use tracing_subscriber::EnvFilter;
|
2021-04-15 08:16:42 +00:00
|
|
|
use veloren_network::{ConnectAddr, ListenAddr, Network, Participant, Pid, Promises};
|
2020-04-08 14:26:42 +00:00
|
|
|
|
|
|
|
///This example contains a simple chatserver, that allows to send messages
|
2020-08-26 08:07:22 +00:00
|
|
|
/// between participants, it's neither pretty nor perfect, but it should show
|
|
|
|
/// how to integrate network
|
2020-04-08 14:26:42 +00:00
|
|
|
fn main() {
|
2022-04-02 13:44:07 +00:00
|
|
|
let matches = Command::new("Chat example")
|
2020-04-08 14:26:42 +00:00
|
|
|
.version("0.1.0")
|
|
|
|
.author("Marcel Märtens <marcel.cochem@googlemail.com>")
|
|
|
|
.about("example chat implemented with veloren-network")
|
|
|
|
.arg(
|
2022-04-02 13:44:07 +00:00
|
|
|
Arg::new("mode")
|
|
|
|
.short('m')
|
2020-04-08 14:26:42 +00:00
|
|
|
.long("mode")
|
|
|
|
.takes_value(true)
|
|
|
|
.possible_values(&["server", "client", "both"])
|
|
|
|
.default_value("both")
|
|
|
|
.help(
|
|
|
|
"choose whether you want to start the server or client or both needed for \
|
|
|
|
this program",
|
|
|
|
),
|
|
|
|
)
|
|
|
|
.arg(
|
2022-04-02 13:44:07 +00:00
|
|
|
Arg::new("port")
|
|
|
|
.short('p')
|
2020-04-08 14:26:42 +00:00
|
|
|
.long("port")
|
|
|
|
.takes_value(true)
|
|
|
|
.default_value("52000")
|
|
|
|
.help("port to listen on"),
|
|
|
|
)
|
|
|
|
.arg(
|
2022-04-02 13:44:07 +00:00
|
|
|
Arg::new("ip")
|
2020-04-08 14:26:42 +00:00
|
|
|
.long("ip")
|
|
|
|
.takes_value(true)
|
|
|
|
.default_value("127.0.0.1")
|
|
|
|
.help("ip to listen and connect to"),
|
|
|
|
)
|
|
|
|
.arg(
|
2022-04-02 13:44:07 +00:00
|
|
|
Arg::new("protocol")
|
2020-04-08 14:26:42 +00:00
|
|
|
.long("protocol")
|
|
|
|
.takes_value(true)
|
|
|
|
.default_value("tcp")
|
|
|
|
.possible_values(&["tcp", "upd", "mpsc"])
|
|
|
|
.help(
|
|
|
|
"underlying protocol used for this test, mpsc can only combined with mode=both",
|
|
|
|
),
|
|
|
|
)
|
|
|
|
.arg(
|
2022-04-02 13:44:07 +00:00
|
|
|
Arg::new("trace")
|
|
|
|
.short('t')
|
2020-04-08 14:26:42 +00:00
|
|
|
.long("trace")
|
|
|
|
.takes_value(true)
|
|
|
|
.default_value("warn")
|
|
|
|
.possible_values(&["trace", "debug", "info", "warn", "error"])
|
|
|
|
.help("set trace level, not this has a performance impact!"),
|
|
|
|
)
|
|
|
|
.get_matches();
|
|
|
|
|
|
|
|
let trace = matches.value_of("trace").unwrap();
|
|
|
|
let filter = EnvFilter::from_default_env().add_directive(trace.parse().unwrap());
|
|
|
|
tracing_subscriber::FmtSubscriber::builder()
|
|
|
|
.with_max_level(Level::TRACE)
|
|
|
|
.with_env_filter(filter)
|
|
|
|
.init();
|
|
|
|
|
|
|
|
let port: u16 = matches.value_of("port").unwrap().parse().unwrap();
|
|
|
|
let ip: &str = matches.value_of("ip").unwrap();
|
2021-04-15 08:16:42 +00:00
|
|
|
let addresses = match matches.value_of("protocol") {
|
|
|
|
Some("tcp") => (
|
|
|
|
ListenAddr::Tcp(format!("{}:{}", ip, port).parse().unwrap()),
|
|
|
|
ConnectAddr::Tcp(format!("{}:{}", ip, port).parse().unwrap()),
|
|
|
|
),
|
|
|
|
Some("udp") => (
|
|
|
|
ListenAddr::Udp(format!("{}:{}", ip, port).parse().unwrap()),
|
|
|
|
ConnectAddr::Udp(format!("{}:{}", ip, port).parse().unwrap()),
|
|
|
|
),
|
2020-04-08 14:26:42 +00:00
|
|
|
_ => panic!("invalid mode, run --help!"),
|
|
|
|
};
|
|
|
|
|
|
|
|
let mut background = None;
|
|
|
|
match matches.value_of("mode") {
|
2021-04-15 08:16:42 +00:00
|
|
|
Some("server") => server(addresses.0),
|
|
|
|
Some("client") => client(addresses.1),
|
2020-04-08 14:26:42 +00:00
|
|
|
Some("both") => {
|
2021-04-15 08:16:42 +00:00
|
|
|
let s = addresses.0;
|
|
|
|
background = Some(thread::spawn(|| server(s)));
|
2020-04-08 14:26:42 +00:00
|
|
|
thread::sleep(Duration::from_millis(200)); //start client after server
|
2021-04-15 08:16:42 +00:00
|
|
|
client(addresses.1)
|
2020-04-08 14:26:42 +00:00
|
|
|
},
|
|
|
|
_ => panic!("invalid mode, run --help!"),
|
|
|
|
};
|
|
|
|
if let Some(background) = background {
|
|
|
|
background.join().unwrap();
|
|
|
|
}
|
|
|
|
}
|
|
|
|
|
2021-04-15 08:16:42 +00:00
|
|
|
fn server(address: ListenAddr) {
|
2021-01-15 13:04:32 +00:00
|
|
|
let r = Arc::new(Runtime::new().unwrap());
|
2021-03-03 09:39:21 +00:00
|
|
|
let server = Network::new(Pid::new(), &r);
|
2020-06-08 09:47:39 +00:00
|
|
|
let server = Arc::new(server);
|
2020-07-13 21:13:54 +00:00
|
|
|
let participants = Arc::new(RwLock::new(Vec::new()));
|
2021-01-15 13:04:32 +00:00
|
|
|
r.block_on(async {
|
2020-04-08 14:26:42 +00:00
|
|
|
server.listen(address).await.unwrap();
|
|
|
|
loop {
|
2020-07-09 07:58:21 +00:00
|
|
|
let p1 = Arc::new(server.connected().await.unwrap());
|
2020-04-08 14:26:42 +00:00
|
|
|
let server1 = server.clone();
|
2020-07-13 21:13:54 +00:00
|
|
|
participants.write().await.push(p1.clone());
|
2021-01-15 13:04:32 +00:00
|
|
|
tokio::spawn(client_connection(server1, p1, participants.clone()));
|
2020-04-08 14:26:42 +00:00
|
|
|
}
|
|
|
|
});
|
|
|
|
}
|
|
|
|
|
2020-08-26 08:07:22 +00:00
|
|
|
async fn client_connection(
|
|
|
|
_network: Arc<Network>,
|
|
|
|
participant: Arc<Participant>,
|
|
|
|
participants: Arc<RwLock<Vec<Arc<Participant>>>>,
|
|
|
|
) {
|
2020-04-08 14:26:42 +00:00
|
|
|
let mut s1 = participant.opened().await.unwrap();
|
|
|
|
let username = s1.recv::<String>().await.unwrap();
|
|
|
|
println!("[{}] connected", username);
|
|
|
|
loop {
|
|
|
|
match s1.recv::<String>().await {
|
|
|
|
Err(_) => {
|
|
|
|
break;
|
|
|
|
},
|
|
|
|
Ok(msg) => {
|
|
|
|
println!("[{}]: {}", username, msg);
|
2020-07-13 21:13:54 +00:00
|
|
|
for p in participants.read().await.iter() {
|
2021-02-18 00:01:57 +00:00
|
|
|
match p
|
|
|
|
.open(4, Promises::ORDERED | Promises::CONSISTENCY, 0)
|
|
|
|
.await
|
|
|
|
{
|
2020-08-26 08:07:22 +00:00
|
|
|
Err(_) => info!("error talking to client, //TODO drop it"),
|
2020-06-08 09:47:39 +00:00
|
|
|
Ok(mut s) => s.send((username.clone(), msg.clone())).unwrap(),
|
|
|
|
};
|
2020-04-08 14:26:42 +00:00
|
|
|
}
|
|
|
|
},
|
|
|
|
}
|
|
|
|
}
|
|
|
|
println!("[{}] disconnected", username);
|
|
|
|
}
|
|
|
|
|
2021-04-15 08:16:42 +00:00
|
|
|
fn client(address: ConnectAddr) {
|
2021-01-15 13:04:32 +00:00
|
|
|
let r = Arc::new(Runtime::new().unwrap());
|
2021-03-03 09:39:21 +00:00
|
|
|
let client = Network::new(Pid::new(), &r);
|
2020-04-08 14:26:42 +00:00
|
|
|
|
2021-01-15 13:04:32 +00:00
|
|
|
r.block_on(async {
|
2020-04-08 14:26:42 +00:00
|
|
|
let p1 = client.connect(address.clone()).await.unwrap(); //remote representation of p1
|
|
|
|
let mut s1 = p1
|
2021-02-18 00:01:57 +00:00
|
|
|
.open(4, Promises::ORDERED | Promises::CONSISTENCY, 0)
|
2020-04-08 14:26:42 +00:00
|
|
|
.await
|
|
|
|
.unwrap(); //remote representation of s1
|
2021-01-15 13:04:32 +00:00
|
|
|
let mut input_lines = io::BufReader::new(io::stdin());
|
2020-04-08 14:26:42 +00:00
|
|
|
println!("Enter your username:");
|
|
|
|
let mut username = String::new();
|
2021-01-15 13:04:32 +00:00
|
|
|
input_lines.read_line(&mut username).await.unwrap();
|
2020-04-08 14:26:42 +00:00
|
|
|
username = username.split_whitespace().collect();
|
|
|
|
println!("Your username is: {}", username);
|
|
|
|
println!("write /quit to close");
|
2021-01-15 13:04:32 +00:00
|
|
|
tokio::spawn(read_messages(p1));
|
2020-04-08 14:26:42 +00:00
|
|
|
s1.send(username).unwrap();
|
|
|
|
loop {
|
|
|
|
let mut line = String::new();
|
2021-01-15 13:04:32 +00:00
|
|
|
input_lines.read_line(&mut line).await.unwrap();
|
2020-04-08 14:26:42 +00:00
|
|
|
line = line.split_whitespace().collect();
|
|
|
|
if line.as_str() == "/quit" {
|
|
|
|
println!("goodbye");
|
|
|
|
break;
|
|
|
|
} else {
|
|
|
|
s1.send(line).unwrap();
|
|
|
|
}
|
|
|
|
}
|
|
|
|
});
|
|
|
|
thread::sleep(Duration::from_millis(30)); // TODO: still needed for correct shutdown
|
|
|
|
}
|
|
|
|
|
|
|
|
// I am quite lazy, the sending is done in a single stream above, but for
|
|
|
|
// receiving i open and close a stream per message. this can be done easier but
|
|
|
|
// this allows me to be quite lazy on the server side and just get a list of
|
|
|
|
// all participants and send to them...
|
2020-07-09 07:58:21 +00:00
|
|
|
async fn read_messages(participant: Participant) {
|
2020-04-08 14:26:42 +00:00
|
|
|
while let Ok(mut s) = participant.opened().await {
|
|
|
|
let (username, message) = s.recv::<(String, String)>().await.unwrap();
|
|
|
|
println!("[{}]: {}", username, message);
|
|
|
|
}
|
|
|
|
println!("gracefully shut down");
|
|
|
|
}
|