Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

How to not crash when a socket fails to connect

I am building a bitcoin clone that needs to be able to connect to other sockets and send information between them. How do I try to connect to another socket and if the socket doesn’t respond just continue with the code instead of crashing the whole program?

This is kind of what I think the code would look like:

use std::io::prelude::*;
use std::net::TcpStream;

fn main()
{
    for node in nodes {
        let mut stream = TcpStream::connect(node).unwrap();
        if successful_connection {
            break;
        }
    }
}

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

>Solution :

The problem is that you use unwrap(). From its docs:

Panics if the value is an Err, with a panic message provided by the Err’s value.

This function’s purpose is to abort your program if the operation has failed, and so:

Because this function may panic, its use is generally discouraged. Instead, prefer to use pattern matching and handle the Err case explicitly, or call unwrap_or, unwrap_or_else, or unwrap_or_default.

In case you want to do something only if the operation has succeeded, and do nothing in the other case, if let is your best friend:

if let Ok(stream) = TcpStream::connect(node) {
    // Do something with `stream`
}

If you also want to handle the error case, you can use match:

match TcpStream::connect(node) {
    Ok(stream) => {
        // Do something with `stream`
    }
    Err(error) => {
        // Handle the error
    }
}
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading