Course of Raku / Functional, concurrent, reactive, and web programming / Web programming / Making remote connections / Exercises / Connect to a host

Solution: Connect to a host

Here is a possible solution to the task.

Code

my $host = 'example.com';

if try IO::Socket::INET.new(:host($host), :port(80)) -> $conn {
    say "connected to $host";
    $conn.close;
}
else {
    say "could not connect to $host";
}

🦋 You can find the source code in the file connect-to-host.raku.

Output

connected to example.com

Comments

  1. IO::Socket::INET.new(:host, :port) opens the connection immediately, and throws if the host is unreachable.

  2. Wrapping it in try turns that exception into a Nil instead of a crash. The if … -> $conn binds the socket when the connection succeeds and runs the else branch when it does not — the robust way to attempt a connection.

Course navigation

Connect to a host   |   Send and receive