Mio : TcpStream::Connect always return success

I'm using mio and TcpStream::connect always return Ok even if there is no server started. Did I miss something ?

fn main() {
let socket = SocketAddr::new(IpAddr::V4(Ipv4Addr::new(127, 0, 0, 1)), 12345);

let result = TcpStream::connect(&socket);
match result {
    Ok(stream) => {
        println!("success");
    },
    Err(e) => {
        println!("{}", e);
    },
}

}

I would guess it has to do with the bit in the documentation about registering handles.

The code example in that section contains the comment,

// The connect is not guaranteed to have started until it is registered at
// this point.

So your "TcpStream" is more of a promise to try to acquire a TcpStream later. Otherwise your code would be blocking trying to connect to a remote host, which is exactly what you're trying to avoid by using mio.

As a side note, you can create your socket more ergonomically by making use of the various From implementations on SocketAddr and IpAddr:

let result = TcpStream::connect(([127, 0, 0, 1], 12345).into())
1 Like

mio is for async network programming. As such the connect call sets up socket for a connection. It can not however connect immediately as that would block. You are suppose to then register the socket with Poll and wait for connection to be established.