A Webget Client

Here’s a simple client that contacts a remote server and fetches a list of documents from it. This is a more interesting client than the previous one because it sends a line of data to the server before fetching that server’s response.

use IO::Socket;
unless (@ARGV > 1) { die "usage: $0 host document ..." }
$host = shift(@ARGV);
foreach $document ( @ARGV ) {
 $remote = IO::Socket::INET->new( Proto => "tcp",
 PeerAddr => $host,
 PeerPort => "http(80)",
 );
 unless ($remote) { die "cannot connect to http daemon on $host" }
 $remote->autoflush(1);
 print $remote "GET $document HTTP/1.0\n\n";
 while ( <$remote> ) { print }
 close $remote;
}

The web server handling the http service is assumed to be at its standard port, number 80. If the server you’re trying to connect to is at a different port (say, 8080), you should give PeerPort => 8080 as the third argument to new(). The autoflush method is used on the socket because otherwise the system would buffer up the output we sent.

Connecting to the server is only the first part of the process: after you have the connection, you have to use the server’s language. Each server on the network has its own little command language that it expects as input. The string that we send to the server starting with GET is in HTTP syntax. In this case, we simply request each specified document. Yes, we really are making a new connection for each document, even though it’s the same host. That’s the way it works with HTTP. (Recent versions of web browsers ...

Get Learning Perl on Win32 Systems now with the O’Reilly learning platform.

O’Reilly members experience books, live events, courses curated by job role, and more from O’Reilly and nearly 200 top publishers.