The answer by @ker will always wait 5 seconds, even if the connection finishes more quickly. Here is a similar approach where the timeout and network request both happen on separate threads, and the first one finished wins:
let (sender, receiver) = mpsc::channel();
let tsender = sender.clone();
let t = thread::spawn(move || {
match sender.send(Ok(net::TcpStream::connect((host.as_str(), port)))) {
Ok(()) => {}, // everything good
Err(_) => {}, // we have been released, don't panic
}
});
let timer = thread::spawn(move || {
thread::sleep(Duration::from_millis(5000));
match tsender.send(Err(MyTimeoutError)) {
Ok(()) => {}, // oops, we timed out
Err(_) => {}, // great, the request finished already
}
});
return receiver.recv().unwrap();
But as long as you're doing that, you might as well just use recv_timeout
instead:
let (sender, receiver) = mpsc::channel();
let t = thread::spawn(move || {
match sender.send(net::TcpStream::connect((host.as_str(), port))) {
Ok(()) => {}, // everything good
Err(_) => {}, // we have been released, don't panic
}
});
return receiver.recv_timeout(Duration::from_millis(5000));
loop {}
and your attempts at killing it.argparse
crate import is not necessary