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.comComments
IO::Socket::INET.new(:host, :port)opens the connection immediately, and throws if the host is unreachable.Wrapping it in
tryturns that exception into aNilinstead of a crash. Theif … -> $connbinds the socket when the connection succeeds and runs theelsebranch when it does not — the robust way to attempt a connection.