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

Sending and receiving

Once a socket is open, you exchange data through it. Send text with .print, and read what comes back with .recv:

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

$conn.print("GET / HTTP/1.0\r\nHost: example.com\r\n\r\n");
my $response = $conn.recv;

$conn.close;
say $response.lines.first;

This sends a minimal HTTP request and reads the server’s reply into $response. The first line of a reply from a web server is its status line.

This example needs a working network connection. When run, it prints a line such as HTTP/1.1 200 OK.

Two details matter when talking to servers. First, network protocols usually separate lines with \r\n (carriage return plus newline), not a plain \n, which is why the request is written with \r\n. Second, .recv returns whatever data has arrived so far; for larger replies you read in a loop until the connection closes.

Sending bytes and receiving bytes is all a socket really does. Everything else — HTTP, and the higher-level tools in the coming sections — is built on top of this simple send-and-receive.

Course navigation

Quiz — Sockets   |   Connect to a host


💪 Or jump directly to the exercises in this section.