read variables from a config file
This commit is contained in:
40
src/main.rs
40
src/main.rs
@@ -1,11 +1,31 @@
|
||||
use std::error::Error;
|
||||
use std::fs;
|
||||
use std::time::Duration;
|
||||
|
||||
use rcon::Connection;
|
||||
use serde::Deserialize;
|
||||
use tokio::time::Instant;
|
||||
use tokio::{io::copy_bidirectional, main};
|
||||
use tokio::net::{TcpListener, TcpStream};
|
||||
|
||||
#[derive(Debug, Deserialize)]
|
||||
struct Config {
|
||||
listen_addr: String,
|
||||
server_addr: String,
|
||||
rcon_addr: String,
|
||||
rcon_password: String,
|
||||
idle_timeout_secs: u64,
|
||||
polling_interval_millis: u64,
|
||||
}
|
||||
|
||||
impl Config {
|
||||
fn load(path: &str) -> Result<Self, Box<dyn Error>> {
|
||||
let content = fs::read_to_string(path)?;
|
||||
let config: Config = toml::from_str(&content)?;
|
||||
Ok(config)
|
||||
}
|
||||
}
|
||||
|
||||
fn parse_players_online(s: &str) -> Option<u32> {
|
||||
s.split_whitespace()
|
||||
.find_map(|tok| tok.parse::<u32>().ok())
|
||||
@@ -13,24 +33,24 @@ fn parse_players_online(s: &str) -> Option<u32> {
|
||||
|
||||
#[main]
|
||||
async fn main() -> Result<(), Box<dyn Error>> {
|
||||
let listen_addr = "0.0.0.0:8080";
|
||||
let server_addr = "127.0.0.1:25565";
|
||||
let rcon_addr = "127.0.0.1:25575";
|
||||
let config = Config::load("config.toml")?;
|
||||
|
||||
println!("Listening on {listen_addr}");
|
||||
println!("Proxying to {server_addr}");
|
||||
println!("Listening on {}", config.listen_addr);
|
||||
println!("Proxying to {}", config.server_addr);
|
||||
|
||||
let listener = TcpListener::bind(listen_addr).await?;
|
||||
let listener = TcpListener::bind(&config.listen_addr).await?;
|
||||
let server_addr = config.server_addr.clone();
|
||||
|
||||
tokio::spawn(async move {
|
||||
let mut conn = <Connection<TcpStream>>::builder()
|
||||
.enable_minecraft_quirks(true)
|
||||
.connect(rcon_addr, "Lusia669")
|
||||
.connect(&config.rcon_addr, &config.rcon_password)
|
||||
.await.unwrap();
|
||||
|
||||
let mut idle = false;
|
||||
let mut last_online = Instant::now();
|
||||
let idle_timeout = Duration::from_secs(10);
|
||||
let idle_timeout = Duration::from_secs(config.idle_timeout_secs);
|
||||
let polling_interval = Duration::from_millis(config.polling_interval_millis);
|
||||
|
||||
loop {
|
||||
let players_cmd_output = conn.cmd("list").await.unwrap();
|
||||
@@ -50,12 +70,12 @@ async fn main() -> Result<(), Box<dyn Error>> {
|
||||
idle = false;
|
||||
}
|
||||
|
||||
tokio::time::sleep(Duration::from_millis(250)).await;
|
||||
tokio::time::sleep(polling_interval).await;
|
||||
};
|
||||
});
|
||||
|
||||
while let Ok((mut inbound, _)) = listener.accept().await {
|
||||
let mut outbound = TcpStream::connect(server_addr).await?;
|
||||
let mut outbound = TcpStream::connect(&server_addr).await?;
|
||||
|
||||
tokio::spawn(async move {
|
||||
if let Err(e) = copy_bidirectional(&mut inbound, &mut outbound).await {
|
||||
|
||||
Reference in New Issue
Block a user