Search code examples
rustrust-tokiotcpsocket

How to set TCP keepalive in tokio?


I noticed that a set_keepalive method was available in Tokio 0.1:

pub fn set_keepalive(&self, keepalive: Option<Duration>) -> Result<(), Error>

But it was removed in the latest 1.0 version (docs). How can I set it now?


Solution

  • Direct support is blocked by this issue. A workaround is available by using the socket2 crate to configure the underlying TCP connection:

    use socket2::{SockRef, TcpKeepalive};
    
    let tcp = TcpStream::connect(&addr).await?;
    
    let ka = TcpKeepalive::new().with_time(std::time::Duration::from_secs(30));
    let sf = SockRef::from(&tcp);
    sf.set_tcp_keepalive(&ka)?;