veloren/client/examples/chat-cli/main.rs

113 lines
2.9 KiB
Rust
Raw Normal View History

2019-08-19 12:39:23 +00:00
#![deny(unsafe_code)]
#![allow(clippy::option_map_unit_fn)]
#![deny(clippy::clone_on_ref_ptr)]
2019-08-19 12:39:23 +00:00
use common::{clock::Clock, comp};
use std::{
io,
sync::{mpsc, Arc},
thread,
time::Duration,
};
use tokio::runtime::Runtime;
use tracing::{error, info};
use veloren_client::{addr::ConnectionArgs, Client, Event};
2019-06-08 23:49:48 +00:00
const TPS: u64 = 10; // Low value is okay, just reading messages.
2019-06-17 10:40:19 +00:00
fn read_input() -> String {
let mut buffer = String::new();
2019-06-17 10:40:50 +00:00
io::stdin()
.read_line(&mut buffer)
2019-06-17 10:40:19 +00:00
.expect("Failed to read input");
buffer.trim().to_string()
2019-06-17 10:40:19 +00:00
}
fn main() {
// Initialize logging.
tracing_subscriber::fmt::init();
info!("Starting chat-cli...");
// Set up an fps clock.
let mut clock = Clock::new(Duration::from_secs_f64(1.0 / TPS as f64));
2019-06-17 13:07:55 +00:00
println!("Enter your username");
2019-07-01 15:15:50 +00:00
let username = read_input();
2019-06-17 13:07:55 +00:00
println!("Enter the server address");
let server_addr = read_input();
2019-08-08 03:56:02 +00:00
println!("Enter your password");
let password = read_input();
let runtime = Arc::new(Runtime::new().unwrap());
let runtime2 = Arc::clone(&runtime);
// Create a client.
let mut client = runtime
.block_on(Client::new(
ConnectionArgs::HostnameAndOptionalPort(server_addr, false),
None,
runtime2,
))
.expect("Failed to create client instance");
2020-12-05 11:47:31 +00:00
println!("Server info: {:?}", client.server_info());
2019-06-02 14:35:21 +00:00
println!("Players online: {:?}", client.get_players());
runtime
.block_on(client.register(username, password, |provider| {
provider == "https://auth.veloren.net"
}))
.unwrap();
2019-06-17 13:07:55 +00:00
let (tx, rx) = mpsc::channel();
thread::spawn(move || {
loop {
let msg = read_input();
tx.send(msg).unwrap();
}
2019-06-17 13:07:55 +00:00
});
loop {
2019-06-17 13:07:55 +00:00
for msg in rx.try_iter() {
client.send_chat(msg)
}
let events = match client.tick(comp::ControllerInputs::default(), clock.dt(), |_| {}) {
Ok(events) => events,
Err(err) => {
error!("Error: {:?}", err);
break;
},
};
const SHOW_NAME: bool = false;
for event in events {
match event {
Event::Chat(m) => println!("{}", client.format_message(&m, SHOW_NAME)),
Event::Disconnect => {}, // TODO
Event::DisconnectionNotification(time) => {
let message = match time {
0 => String::from("Goodbye!"),
_ => format!("Connection lost. Kicking in {} seconds", time),
};
println!("{}", message)
},
2020-06-25 18:50:04 +00:00
_ => {},
}
}
// Clean up the server after a tick.
client.cleanup();
// Wait for the next tick.
clock.tick();
}
}