So basically I want to write/read to a TcpStream
, but am struggling with a few things.
First TcpStream::read
doesn't seem to be blocking, so I did a simple sleep
but that's a bit of a half-assed work, so I'd like to know if anyone can help me with that. Second of all, if I try to send a number bigger than 248 it doesn't send it all, just sends 64.
Code:
use std::io::prelude::*;
use std::net::{TcpListener, TcpStream};
use std::thread;
use std::sync::{Arc, RwLock};
use std::io::prelude::*;
use std::time::Duration;
static IP: &'static str = "127.0.0.1:34254";
fn alertMessage() {
println!("Bound to IP: {}", IP);
}
fn read(stream: &mut TcpStream) {
let mut buf = Vec::new();
println!("Received {} bytes", stream.read_to_end(&mut buf).unwrap());
println!("[{:?}] Receiving: {:?}", thread::current().name().unwrap(), buf);
}
fn main() {
let listener = TcpListener::bind(IP).unwrap();
alertMessage();
let lcln = listener.try_clone().unwrap();
let handle = thread::spawn(move || loop {
match lcln.accept() {
Ok((mut _socket, addr)) => {
println!("new client: {:?}", addr);
thread::Builder::new().name("Reader".to_string()).spawn(move || loop {
read(&mut _socket);
thread::sleep(Duration::from_secs(5));
});
},
Err(e) => println!("couldn't get client: {:?}", e),
}
});
if let Ok(mut stream) = TcpStream::connect("127.0.0.1:34254") {
let mut s = 248;
thread::Builder::new().name("Sender".to_string()).spawn(move ||
for i in (0..10) {
s+=1;
println!("[{:?}] Sending: {}", thread::current().name().unwrap(), s);
stream.write_all(&[200000]);
});
}
handle.join();
}
Outputs:
Bound to IP: 127.0.0.1:34254
new client: V4(127.0.0.1:58428)
["Sender"] Sending: 249
["Sender"] Sending: 250
["Sender"] Sending: 251
["Sender"] Sending: 252
["Sender"] Sending: 253
["Sender"] Sending: 254
["Sender"] Sending: 255
["Sender"] Sending: 256
["Sender"] Sending: 257
["Sender"] Sending: 258
Received 10 bytes
["Reader"] Receiving: [64, 64, 64, 64, 64, 64, 64, 64, 64, 64]
And then every 5 seconds:
Received 0 bytes
["Reader"] Receiving: []
If I remove the sleep
then the output becomes full off those. Read is not blocking at all.
Thanks for the your time reading this!