Start local server on client run
This commit is contained in:
2
rust/sea_battle_backend/src/utils/mod.rs
Normal file
2
rust/sea_battle_backend/src/utils/mod.rs
Normal file
@@ -0,0 +1,2 @@
|
||||
pub mod network_utils;
|
||||
pub mod string_utils;
|
22
rust/sea_battle_backend/src/utils/network_utils.rs
Normal file
22
rust/sea_battle_backend/src/utils/network_utils.rs
Normal file
@@ -0,0 +1,22 @@
|
||||
use std::time::Duration;
|
||||
|
||||
use tokio::net::TcpStream;
|
||||
use tokio::time;
|
||||
|
||||
/// Check whether a given port is open or not
|
||||
pub async fn is_port_open(port: u16) -> bool {
|
||||
TcpStream::connect(("127.0.0.1", port)).await.is_ok()
|
||||
}
|
||||
|
||||
/// Wait for a port to become available
|
||||
pub async fn wait_for_port(port: u16) {
|
||||
for _ in 0..50 {
|
||||
if is_port_open(port).await {
|
||||
return;
|
||||
}
|
||||
time::sleep(Duration::from_millis(10)).await;
|
||||
}
|
||||
|
||||
eprintln!("Port {} did not open in time!", port);
|
||||
std::process::exit(2);
|
||||
}
|
23
rust/sea_battle_backend/src/utils/string_utils.rs
Normal file
23
rust/sea_battle_backend/src/utils/string_utils.rs
Normal file
@@ -0,0 +1,23 @@
|
||||
use rand::distributions::Alphanumeric;
|
||||
use rand::{thread_rng, Rng};
|
||||
|
||||
/// Generate a random string of a given size
|
||||
pub fn rand_str(len: usize) -> String {
|
||||
thread_rng()
|
||||
.sample_iter(&Alphanumeric)
|
||||
.map(char::from)
|
||||
.take(len)
|
||||
.collect()
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod test {
|
||||
use crate::utils::string_utils::rand_str;
|
||||
|
||||
#[test]
|
||||
fn test_rand_str() {
|
||||
let size = 10;
|
||||
let rand = rand_str(size);
|
||||
assert_eq!(size, rand.len());
|
||||
}
|
||||
}
|
Reference in New Issue
Block a user