set read timeout

This commit is contained in:
Robin Mueller
2025-11-04 16:39:56 +01:00
parent 00dc99d697
commit 4eecde23b7

View File

@@ -1,5 +1,5 @@
//! # Packet transport via TCP with COBS encoding.
use std::io::{Read as _, Write as _};
use std::{io::{Read as _, Write as _}, time::Duration};
use crate::transport::PacketTransport;
@@ -20,6 +20,7 @@ impl PacketTransportTcpWithCobs {
/// The `tcp_stream` parameter is the underlying TCP stream which should already be connected.
pub fn new(tcp_stream: std::net::TcpStream, decoder: cobs::CobsDecoderOwned) -> Self {
tcp_stream.set_nonblocking(true).unwrap();
tcp_stream.set_read_timeout(Some(Duration::from_millis(100))).unwrap();
Self {
tcp_stream,
decoder,
@@ -42,6 +43,9 @@ impl PacketTransportTcpWithCobs {
/// This function pulls bytes from the TCP stream and feeds them into the COBS decoder.
/// For each received packet, the closure will be called with the decoded packet as an argument.
/// The function will return the number of received packets.
///
/// Please note that this function may block on the TCP stream read call, but it will not
/// block indifinitely due to the read timeout set on the TCP stream.
pub fn receive(&mut self, mut f: impl FnMut(&[u8])) -> Result<usize, super::ReceiveError> {
let mut decoded_packets = 0;
loop {