Hello everyone
i created a small program which count the number of bytes of a file sent over a socket, the program looks like this
use std::time::Instant;
use tokio::net::TcpListener;
use tokio::io::Result;
use tokio::io::BufReader;
use tokio::io::AsyncReadExt;
use console::style;
#[tokio::main]
async fn main() -> Result<()> {
let mut listener = TcpListener::bind("127.0.0.1:2020").await?;
println!("[ {} ] Wating for files..", style("START").bold().green());
loop {
let (mut stream, addr) = listener.accept().await?;
let now = Instant::now();
println!(
"[ {} ] Processing file from {}",
style("NEW").bold().yellow(),
style(addr).magenta()
);
let (reader, _) = stream.split();
let mut reader = BufReader::new(reader);
let mut buf = [0; 1024];
let mut nb_alphas = 0;
while let Ok(len) = reader.read(&mut buf).await {
if len == 0 { break }
for b in buf.iter() {
match *b {
b'a'..=b'z' | b'A'..=b'Z' => {
nb_alphas += 1;
},
_ => { }
}
}
}
println!();
println!(" > Number of alphas: {}", nb_alphas);
// --
let elapsed = now.elapsed();
println!(
"\n--\n{} {}\t{} {}",
style(elapsed.as_secs_f64()).cyan(),
style("secs").bold(),
style(elapsed.as_nanos()).cyan(),
style("nanos").bold()
);
}
}
i send a file using socat like this socat -u FILE:file.txt TCP:127.0.0.1:2020
but the weird thing, is everytime i run th eprogram, the alphas counter gives me different results, and i have no idea why?
this is the output, after a few runs
[ START ] Wating for files..
[ NEW ] Processing file from 127.0.0.1:41516
> Number of alphas: 694712146
--
2.718421352 secs 2718421352 nanos
[ NEW ] Processing file from 127.0.0.1:41518
> Number of alphas: 694712160
--
2.73934149 secs 2739341490 nanos
[ NEW ] Processing file from 127.0.0.1:41520
> Number of alphas: 694712159
--
2.726005681 secs 2726005681 nanos
[ NEW ] Processing file from 127.0.0.1:41522
> Number of alphas: 694712171
--
2.737450261 secs 2737450261 nanos