Why doesn’t TcpStream::connect_timeout() retry the connection?

I have the following source code that should try to connect to a server for 200 seconds. After that time, it should return an error.

Plain text
Copy to clipboard
Open code in new window
EnlighterJS 3 Syntax Highlighter
<code>use std::{
io::{self, Result, Write},
net::{SocketAddr, TcpStream},
time::Duration,
};
struct Client {
channel: Option<TcpStream>,
}
impl Client {
fn new() -> Self {
Self { channel: None }
}
fn connect(&mut self, addr: SocketAddr, duration: Duration) -> Result<()> {
let connection = TcpStream::connect_timeout(&addr, duration)?;
self.channel = Some(connection);
Ok(())
}
fn send(&mut self, msg: &[u8]) -> Result<()> {
self.channel
.as_mut()
.ok_or(io::Error::new(io::ErrorKind::NotConnected, "Not connected"))?
.write_all(msg)?;
Ok(())
}
}
fn main() {
let mut client = Client::new();
println!("Waiting to connect to server...");
let result_conn = client.connect(
SocketAddr::from(([127, 0, 0, 1], 3030)),
Duration::new(200, 0),
);
if result_conn.is_ok() {
let msg = b"Hi, I am Hernan and this is my first client-server program";
println!("Sending message: {:?}", msg);
match client.send(msg) {
Ok(_) => println!("Message sent"),
Err(e) => println!("Failed to send message: {:?}", e),
}
}
if let Err(e) = result_conn {
println!("Fail to connect: {:?}", e);
}
}
</code>
<code>use std::{ io::{self, Result, Write}, net::{SocketAddr, TcpStream}, time::Duration, }; struct Client { channel: Option<TcpStream>, } impl Client { fn new() -> Self { Self { channel: None } } fn connect(&mut self, addr: SocketAddr, duration: Duration) -> Result<()> { let connection = TcpStream::connect_timeout(&addr, duration)?; self.channel = Some(connection); Ok(()) } fn send(&mut self, msg: &[u8]) -> Result<()> { self.channel .as_mut() .ok_or(io::Error::new(io::ErrorKind::NotConnected, "Not connected"))? .write_all(msg)?; Ok(()) } } fn main() { let mut client = Client::new(); println!("Waiting to connect to server..."); let result_conn = client.connect( SocketAddr::from(([127, 0, 0, 1], 3030)), Duration::new(200, 0), ); if result_conn.is_ok() { let msg = b"Hi, I am Hernan and this is my first client-server program"; println!("Sending message: {:?}", msg); match client.send(msg) { Ok(_) => println!("Message sent"), Err(e) => println!("Failed to send message: {:?}", e), } } if let Err(e) = result_conn { println!("Fail to connect: {:?}", e); } } </code>
use std::{
    io::{self, Result, Write},
    net::{SocketAddr, TcpStream},
    time::Duration,
};

struct Client {
    channel: Option<TcpStream>,
}

impl Client {
    fn new() -> Self {
        Self { channel: None }
    }

    fn connect(&mut self, addr: SocketAddr, duration: Duration) -> Result<()> {
        let connection = TcpStream::connect_timeout(&addr, duration)?;
        self.channel = Some(connection);
        Ok(())
    }

    fn send(&mut self, msg: &[u8]) -> Result<()> {
        self.channel
            .as_mut()
            .ok_or(io::Error::new(io::ErrorKind::NotConnected, "Not connected"))?
            .write_all(msg)?;
        Ok(())
    }
}

fn main() {
    let mut client = Client::new();
    println!("Waiting to connect to server...");
    let result_conn = client.connect(
        SocketAddr::from(([127, 0, 0, 1], 3030)),
        Duration::new(200, 0),
    );

    if result_conn.is_ok() {
        let msg = b"Hi, I am Hernan and this is my first client-server program";
        println!("Sending message: {:?}", msg);
        match client.send(msg) {
            Ok(_) => println!("Message sent"),
            Err(e) => println!("Failed to send message: {:?}", e),
        }
    }
    if let Err(e) = result_conn {
        println!("Fail to connect: {:?}", e);
    }
}

However, when I run the program it immediately returns the error ConnectionRefused instead of trying to connect for 200 seconds as I expected.

I am running this program on Linux Ubuntu 22.04. Why isn’t connect_timeout() blocking the execution and retrying the connection for the specified time?

I attach the source code for the server:

Plain text
Copy to clipboard
Open code in new window
EnlighterJS 3 Syntax Highlighter
<code>use std::{
io::{Read, Result},
net::{SocketAddr, TcpListener, TcpStream},
};
struct Server {
channel: TcpStream,
}
impl Server {
const MAX_BUFF_SIZE: usize = 128;
fn new(addr: SocketAddr) -> Result<Self> {
println!("Waiting for connections...");
let listener = TcpListener::bind(addr)?;
let (stream, socket) = listener.accept()?;
println!("Connection received from {:?}", socket);
Ok(Self { channel: stream })
}
fn recv(&mut self) -> Result<[u8; Self::MAX_BUFF_SIZE]> {
let mut buff = [0; Self::MAX_BUFF_SIZE];
self.channel.read(&mut buff)?;
Ok(buff)
}
}
fn main() -> Result<()> {
let mut server = Server::new(SocketAddr::from(([127, 0, 0, 1], 3030)))?;
let msg = server.recv()?;
println!("Message received: {:?}", msg);
Ok(())
}
</code>
<code>use std::{ io::{Read, Result}, net::{SocketAddr, TcpListener, TcpStream}, }; struct Server { channel: TcpStream, } impl Server { const MAX_BUFF_SIZE: usize = 128; fn new(addr: SocketAddr) -> Result<Self> { println!("Waiting for connections..."); let listener = TcpListener::bind(addr)?; let (stream, socket) = listener.accept()?; println!("Connection received from {:?}", socket); Ok(Self { channel: stream }) } fn recv(&mut self) -> Result<[u8; Self::MAX_BUFF_SIZE]> { let mut buff = [0; Self::MAX_BUFF_SIZE]; self.channel.read(&mut buff)?; Ok(buff) } } fn main() -> Result<()> { let mut server = Server::new(SocketAddr::from(([127, 0, 0, 1], 3030)))?; let msg = server.recv()?; println!("Message received: {:?}", msg); Ok(()) } </code>
use std::{
    io::{Read, Result},
    net::{SocketAddr, TcpListener, TcpStream},
};

struct Server {
    channel: TcpStream,
}

impl Server {
    const MAX_BUFF_SIZE: usize = 128;

    fn new(addr: SocketAddr) -> Result<Self> {
        println!("Waiting for connections...");
        let listener = TcpListener::bind(addr)?;
        let (stream, socket) = listener.accept()?;
        println!("Connection received from {:?}", socket);
        Ok(Self { channel: stream })
    }

    fn recv(&mut self) -> Result<[u8; Self::MAX_BUFF_SIZE]> {
        let mut buff = [0; Self::MAX_BUFF_SIZE];
        self.channel.read(&mut buff)?;
        Ok(buff)
    }
}

fn main() -> Result<()> {
    let mut server = Server::new(SocketAddr::from(([127, 0, 0, 1], 3030)))?;
    let msg = server.recv()?;
    println!("Message received: {:?}", msg);
    Ok(())
}

8

I have found a workaround for this problem to make it work with the requirements posted in the question (as @SteffenUllrich suggested to retry the connection). The new version for the cliend should be as follows:

Plain text
Copy to clipboard
Open code in new window
EnlighterJS 3 Syntax Highlighter
<code>use std::{
io::{self, Result, Write},
net::{SocketAddr, TcpStream},
time::{Duration, Instant},
};
struct Client {
channel: Option<TcpStream>,
}
impl Client {
fn new() -> Self {
Self { channel: None }
}
fn connect(&mut self, addr: SocketAddr, timeout: Duration, retry_time: Duration) -> Result<()> {
let start_time = Instant::now();
loop {
match TcpStream::connect(addr) {
Ok(channel) => {
self.channel = Some(channel);
return Ok(());
}
Err(e) => {
let elapsed_time = start_time.elapsed();
if elapsed_time > timeout {
return Err(e);
}
std::thread::sleep(retry_time);
}
}
}
}
fn send(&mut self, msg: &[u8]) -> Result<()> {
self.channel
.as_mut()
.ok_or(io::Error::new(io::ErrorKind::NotConnected, "Not connected"))?
.write_all(msg)?;
Ok(())
}
}
fn main() {
let mut client = Client::new();
println!("Waiting to connect to server...");
let result_conn = client.connect(
SocketAddr::from(([127, 0, 0, 1], 3030)),
Duration::from_secs(200),
Duration::from_millis(300),
);
if result_conn.is_ok() {
let msg = b"Hi, I am Hernan and this is my first client-server program";
println!("Sending message: {:?}", msg);
match client.send(msg) {
Ok(_) => println!("Message sent"),
Err(e) => println!("Failed to send message: {:?}", e),
}
}
if let Err(e) = result_conn {
println!("Fail to connect: {:?}", e);
}
}
</code>
<code>use std::{ io::{self, Result, Write}, net::{SocketAddr, TcpStream}, time::{Duration, Instant}, }; struct Client { channel: Option<TcpStream>, } impl Client { fn new() -> Self { Self { channel: None } } fn connect(&mut self, addr: SocketAddr, timeout: Duration, retry_time: Duration) -> Result<()> { let start_time = Instant::now(); loop { match TcpStream::connect(addr) { Ok(channel) => { self.channel = Some(channel); return Ok(()); } Err(e) => { let elapsed_time = start_time.elapsed(); if elapsed_time > timeout { return Err(e); } std::thread::sleep(retry_time); } } } } fn send(&mut self, msg: &[u8]) -> Result<()> { self.channel .as_mut() .ok_or(io::Error::new(io::ErrorKind::NotConnected, "Not connected"))? .write_all(msg)?; Ok(()) } } fn main() { let mut client = Client::new(); println!("Waiting to connect to server..."); let result_conn = client.connect( SocketAddr::from(([127, 0, 0, 1], 3030)), Duration::from_secs(200), Duration::from_millis(300), ); if result_conn.is_ok() { let msg = b"Hi, I am Hernan and this is my first client-server program"; println!("Sending message: {:?}", msg); match client.send(msg) { Ok(_) => println!("Message sent"), Err(e) => println!("Failed to send message: {:?}", e), } } if let Err(e) = result_conn { println!("Fail to connect: {:?}", e); } } </code>
use std::{
    io::{self, Result, Write},
    net::{SocketAddr, TcpStream},
    time::{Duration, Instant},
};

struct Client {
    channel: Option<TcpStream>,
}

impl Client {
    fn new() -> Self {
        Self { channel: None }
    }

    fn connect(&mut self, addr: SocketAddr, timeout: Duration, retry_time: Duration) -> Result<()> {
        let start_time = Instant::now();
        loop {
            match TcpStream::connect(addr) {
                Ok(channel) => {
                    self.channel = Some(channel);
                    return Ok(());
                }
                Err(e) => {
                    let elapsed_time = start_time.elapsed();
                    if elapsed_time > timeout {
                        return Err(e);
                    }

                    std::thread::sleep(retry_time);
                }
            }
        }
    }

    fn send(&mut self, msg: &[u8]) -> Result<()> {
        self.channel
            .as_mut()
            .ok_or(io::Error::new(io::ErrorKind::NotConnected, "Not connected"))?
            .write_all(msg)?;
        Ok(())
    }
}

fn main() {
    let mut client = Client::new();
    println!("Waiting to connect to server...");
    let result_conn = client.connect(
        SocketAddr::from(([127, 0, 0, 1], 3030)),
        Duration::from_secs(200),
        Duration::from_millis(300),
    );

    if result_conn.is_ok() {
        let msg = b"Hi, I am Hernan and this is my first client-server program";
        println!("Sending message: {:?}", msg);
        match client.send(msg) {
            Ok(_) => println!("Message sent"),
            Err(e) => println!("Failed to send message: {:?}", e),
        }
    }
    if let Err(e) = result_conn {
        println!("Fail to connect: {:?}", e);
    }
}

Trang chủ Giới thiệu Sinh nhật bé trai Sinh nhật bé gái Tổ chức sự kiện Biểu diễn giải trí Dịch vụ khác Trang trí tiệc cưới Tổ chức khai trương Tư vấn dịch vụ Thư viện ảnh Tin tức - sự kiện Liên hệ Chú hề sinh nhật Trang trí YEAR END PARTY công ty Trang trí tất niên cuối năm Trang trí tất niên xu hướng mới nhất Trang trí sinh nhật bé trai Hải Đăng Trang trí sinh nhật bé Khánh Vân Trang trí sinh nhật Bích Ngân Trang trí sinh nhật bé Thanh Trang Thuê ông già Noel phát quà Biểu diễn xiếc khỉ Xiếc quay đĩa Dịch vụ tổ chức sự kiện 5 sao Thông tin về chúng tôi Dịch vụ sinh nhật bé trai Dịch vụ sinh nhật bé gái Sự kiện trọn gói Các tiết mục giải trí Dịch vụ bổ trợ Tiệc cưới sang trọng Dịch vụ khai trương Tư vấn tổ chức sự kiện Hình ảnh sự kiện Cập nhật tin tức Liên hệ ngay Thuê chú hề chuyên nghiệp Tiệc tất niên cho công ty Trang trí tiệc cuối năm Tiệc tất niên độc đáo Sinh nhật bé Hải Đăng Sinh nhật đáng yêu bé Khánh Vân Sinh nhật sang trọng Bích Ngân Tiệc sinh nhật bé Thanh Trang Dịch vụ ông già Noel Xiếc thú vui nhộn Biểu diễn xiếc quay đĩa Dịch vụ tổ chức tiệc uy tín Khám phá dịch vụ của chúng tôi Tiệc sinh nhật cho bé trai Trang trí tiệc cho bé gái Gói sự kiện chuyên nghiệp Chương trình giải trí hấp dẫn Dịch vụ hỗ trợ sự kiện Trang trí tiệc cưới đẹp Khởi đầu thành công với khai trương Chuyên gia tư vấn sự kiện Xem ảnh các sự kiện đẹp Tin mới về sự kiện Kết nối với đội ngũ chuyên gia Chú hề vui nhộn cho tiệc sinh nhật Ý tưởng tiệc cuối năm Tất niên độc đáo Trang trí tiệc hiện đại Tổ chức sinh nhật cho Hải Đăng Sinh nhật độc quyền Khánh Vân Phong cách tiệc Bích Ngân Trang trí tiệc bé Thanh Trang Thuê dịch vụ ông già Noel chuyên nghiệp Xem xiếc khỉ đặc sắc Xiếc quay đĩa thú vị
Trang chủ Giới thiệu Sinh nhật bé trai Sinh nhật bé gái Tổ chức sự kiện Biểu diễn giải trí Dịch vụ khác Trang trí tiệc cưới Tổ chức khai trương Tư vấn dịch vụ Thư viện ảnh Tin tức - sự kiện Liên hệ Chú hề sinh nhật Trang trí YEAR END PARTY công ty Trang trí tất niên cuối năm Trang trí tất niên xu hướng mới nhất Trang trí sinh nhật bé trai Hải Đăng Trang trí sinh nhật bé Khánh Vân Trang trí sinh nhật Bích Ngân Trang trí sinh nhật bé Thanh Trang Thuê ông già Noel phát quà Biểu diễn xiếc khỉ Xiếc quay đĩa
Thiết kế website Thiết kế website Thiết kế website Cách kháng tài khoản quảng cáo Mua bán Fanpage Facebook Dịch vụ SEO Tổ chức sinh nhật