From e2f9ba78c643ab52e2f3d92dc97fd53876532d43 Mon Sep 17 00:00:00 2001 From: Alex van de Sandt Date: Mon, 18 Mar 2019 17:32:45 +0000 Subject: [PATCH] Buffer reads from clients to gracefullly handle disconnects --- candid_server/src/client_handler.rs | 22 +++++++++++++++++----- 1 file(s) changed, 17 insertion(s)(+), 5 deletion(s)(-) diff --git a/candid_server/src/client_handler.rs b/candid_server/src/client_handler.rs --- a/candid_server/src/client_handler.rs +++ b/candid_server/src/client_handler.rs @@ -1,6 +1,6 @@ -use std::io::{Read, Write}; +use std::io::{BufReader, Read, Write}; use std::net::TcpStream; -use std::sync::{mpsc, Arc, Mutex}; +use std::sync::mpsc; use std::thread; use byteorder::{NetworkEndian, ReadBytesExt}; @@ -34,16 +34,28 @@ // Thread to pass frames from the client to the CAN socket let rx_handle = thread::spawn(move || { - let mut connection = connection_clone; + let ip = connection_clone.peer_addr().unwrap(); + let mut connection = BufReader::new(connection_clone); // Possible issue: There is a new socket for each thread let can_socket = CANSocket::open(&can_interface).unwrap(); loop { // Get an incoming frame from the client - let id = connection.read_u32::().unwrap(); + let id: u32; + match connection.read_u32::() { + Ok(inner) => id = inner, + Err(_) => { + println!("Connection to client {:?} dropped.", ip); + break; + } + } + let mut data = [0 as u8; 8]; - connection.read_exact(&mut data).unwrap(); + if let Err(_) = connection.read_exact(&mut data) { + println!("Connection to client {:?} dropped.", ip); + break; + } let frame = CANFrame::new(id, &data, false, false).unwrap(); println!("New frame {:X}", frame); -- tangled.sh