handle_client now supports multiple messages
This commit is contained in:
parent
0b7f161188
commit
4534abc2cb
2 changed files with 43 additions and 10 deletions
|
@ -23,7 +23,7 @@ impl Socket {
|
|||
let handle = thread::spawn(move || {
|
||||
listener.set_nonblocking(true).unwrap();
|
||||
while thread_stop_flag.get() {
|
||||
for (stream, addr) in listener.accept() {
|
||||
for (stream, _addr) in listener.accept() {
|
||||
Socket::handle_client(stream, messenger_tx.clone());
|
||||
}
|
||||
thread::sleep(Duration::from_millis(100));
|
||||
|
@ -34,17 +34,21 @@ impl Socket {
|
|||
}
|
||||
|
||||
pub fn handle_client(mut stream: TcpStream, update_tx: Sender<String>) {
|
||||
let mut buffer = [0; 1024];
|
||||
let mut buffer = [0; 1024];
|
||||
|
||||
let read_size = stream.read(&mut buffer).unwrap();
|
||||
|
||||
//Tcp is supposed to have a 0 byte read if closed by client
|
||||
if read_size == 0 {
|
||||
stream.shutdown(Shutdown::Both).unwrap();
|
||||
return
|
||||
loop {
|
||||
let read_size = stream.read(&mut buffer).unwrap();
|
||||
|
||||
//Tcp is supposed to have a 0 byte read if closed by client
|
||||
if read_size == 0 {
|
||||
stream.shutdown(Shutdown::Both).unwrap();
|
||||
thread::sleep(Duration::from_millis(75));
|
||||
break;
|
||||
}
|
||||
let output = String::from_utf8_lossy(&buffer[0..read_size]);
|
||||
update_tx.send(output.into_owned()).unwrap();
|
||||
}
|
||||
|
||||
let output = String::from_utf8_lossy(&buffer[0..read_size]);
|
||||
update_tx.send(output.into_owned()).unwrap();
|
||||
|
||||
}
|
||||
}
|
|
@ -48,3 +48,32 @@ fn can_handle_messages() {
|
|||
let message = rx_1.recv().unwrap();
|
||||
assert_eq!(message, String::from("this is a test"));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn can_handle_delayed_messages() {
|
||||
let listener = Socket::make_listener("localhost:5005");
|
||||
let (tx_1, rx_1) = mpsc::channel::<String>();
|
||||
|
||||
let (mut flag, connection_handle) = Socket::handle_connections(listener, tx_1);
|
||||
|
||||
let join_handle = std::thread::spawn(move || {
|
||||
let mut outgoing = std::net::TcpStream::connect("localhost:5005").unwrap();
|
||||
outgoing.write("this is a test1\n".as_bytes()).unwrap();
|
||||
thread::sleep(Duration::from_millis(500));
|
||||
outgoing.write("this is a test3\n".as_bytes()).unwrap();
|
||||
drop(outgoing);
|
||||
});
|
||||
join_handle.join().unwrap();
|
||||
thread::sleep(Duration::from_millis(1000));
|
||||
|
||||
let message = rx_1.recv().unwrap();
|
||||
println!("{}", message);
|
||||
assert_eq!(message, String::from("this is a test1\n"));
|
||||
|
||||
let message = rx_1.recv().unwrap();
|
||||
println!("{}", message);
|
||||
assert_eq!(message, String::from("this is a test3\n"));
|
||||
|
||||
flag.set(false);
|
||||
connection_handle.join().unwrap();
|
||||
}
|
||||
|
|
Loading…
Reference in a new issue