servers/src/main.rs

61 lines
1.7 KiB
Rust
Raw Normal View History

2022-06-04 18:10:21 +00:00
use servers::{loader, Client, CommandManagerType};
2022-06-04 11:58:21 +00:00
use tokio::{io::AsyncWriteExt, net::TcpListener};
#[tokio::main]
async fn main() -> anyhow::Result<()> {
// listen Tcp server
let listener = TcpListener::bind("0.0.0.0:9999").await?;
2022-06-04 18:10:21 +00:00
println!("Tcp server started at: {}", listener.local_addr()?);
2022-06-04 11:58:21 +00:00
2022-06-04 18:10:21 +00:00
// load plugins and commands
let (_plugin_manager, commands_manager) = loader()?;
2022-06-04 11:58:21 +00:00
// Accepts a new incoming connection from this listener.
while let Ok((stream, _address)) = listener.accept().await {
let client = Client::new(stream);
// handle client connection in new thread
2022-06-04 18:10:21 +00:00
tokio::spawn(handle_connection(client, commands_manager.clone()));
2022-06-04 11:58:21 +00:00
}
Ok(())
}
2022-06-04 18:10:21 +00:00
async fn handle_connection(mut client: Client, commands: CommandManagerType) -> anyhow::Result<()> {
2022-06-04 11:58:21 +00:00
println!("New Client: {:?}", client.stream.peer_addr()?);
loop {
// read client message/buffer
let buf = client.read().await?;
// split message by whitespace
let args: &Vec<&str> = &buf.split_ascii_whitespace().collect();
// get command from args
let cmd = args[0];
2022-06-04 18:10:21 +00:00
// search if a command exists
for command in commands.iter() {
// if this is the entered command
2022-06-04 11:58:21 +00:00
if cmd == command.name() {
2022-06-04 18:10:21 +00:00
// execute command
command
.execute(&mut client, args[1..args.len()].to_vec(), &commands)
.await;
2022-06-04 11:58:21 +00:00
2022-06-04 18:10:21 +00:00
// don't search for more commands
break;
2022-06-04 11:58:21 +00:00
}
}
// if an I/O or EOF error, abort the connection
if client.stream.flush().await.is_err() {
2022-06-04 18:10:21 +00:00
// terminate connection
2022-06-04 11:58:21 +00:00
break;
}
}
Ok(())
}