Course of Raku / Functional, concurrent, reactive, and web programming / Web programming / Making remote connections

Opening a socket

A socket is a connection between two programs over a network. Raku’s core class for TCP sockets is IO::Socket::INET, and you need nothing extra installed to use it.

To connect to a remote server, create a socket with the host and port you want to reach:

my $conn = IO::Socket::INET.new(:host('example.com'), :port(80));
say 'connected';
$conn.close;

IO::Socket::INET.new opens the connection straight away. Port 80 is the standard port for HTTP, so this connects to the web server at example.com. When you are finished, .close releases the connection.

This example needs a working network connection to run. When it connects successfully it prints connected.

The same class is used in two modes: as a client, connecting out to a server as shown here, and as a server, listening for connections coming in (which you will see later). For now, the idea to take away is that IO::Socket::INET.new(:host, :port) gives you a live two-way channel to another machine.

Practice

Complete the quiz that covers the contents of this topic.

Course navigation

Making remote connections   |   Quiz — Sockets


💪 Or jump directly to the exercises in this section.