Async read/write from TlsStream with tokio

Hello everybody. I'm pretty new to the rust language and have recently begun working with tokio. I'm currently working on a project where I need to communicate with a server. However the Server can send me data and I can send data to the server independently. Therefore I tried to use tokio::split(), however it seems I can't read from the readhalf. If i get a message I get stuck in an infinit loop of reading 0 bytes. Here's the code:

async fn handle_connection(mut reader: ReadHalf<TlsStream<TcpStream>>) {
    let mut message = String::new();
    loop {
        match reader.read_to_string(&mut message).await {
            Ok(_len) => {
                println!("{}", message);
                message = String::new();
            },
            Err(e) => {
                eprintln!("Lost connection to host. Error {}", e);
                return;
            }
        }
    }
}

it gets called from the connect function:

async fn connect_to_master(stream: TlsStream<TcpStream>) {
    let message = write_netstring(ICINGA_HELLO);
    let (reader, mut writer) = tokio::io::split(stream);

    writer.write(message.as_bytes()).await;
    writer.flush().await;

    tokio::spawn(async { handle_connection(reader).await });

    loop {
        sleep(Duration::from_secs(20));
        writer
            .write(write_netstring(ICINGA_HEARTBEAT).as_bytes())
            .await;
        writer.flush().await;
    }
}

Two comments:

  1. The only situation in which a read would return a length of zero is when the stream has been closed by the other end.
  2. Don't use std::thread::sleep in async code. Read this for more.
1 Like

I figured it out. The call to read_to_string() only returns after the connection has been closed, meaning I wont get any data till then. The infinit loop was an error with the certificate, combined with the fact that it returns 0 when the socket is closed as @alice pointed out.

Thanks, I will look into that.

This topic was automatically closed 90 days after the last reply. We invite you to open a new topic if you have further questions or comments.