Allow non-blocking Read to check socket status

The way to determine if a socket has been closed is to perform a read or write on it. However, without being able to do a non-blocking read, it’s not possible to check the status without blocking. There is a ErrorKind::WouldBlock, which at first led me to think this might be possible.

I’m not asking for full async IO. Just to be able to try a possible read that isn’t blocking. Take an example ConnectionPool, which wants to check that a pooled connection is still alive before returning it:

fn get(addr: SocketAddr) -> TcpStream {
    if let Some(ref mut pooled) = self.conns.find(&addr) {
        while let Some(mut conn) = pooled.pop() {
            match conn.read_nonblocking(&[]) {
                Ok(..) => return conn,
                Err(e) if e.kind() == ErrorKind::WouldBlock => return conn,
                Err(..) => continue
            }
        }
    }
    // all dead, TcpStream::connect() a new one
}
3 Likes

This topic was automatically closed 90 days after the last reply. New replies are no longer allowed.