Web-Clients


Ein einfacher Client

Wir wollen mit einem Perl-Skript einen Web-Server direkt ansprechen. Dazu schreiben wir ein gethttp Programm, das eine URL als Argument bekommt, und diese dann beim entsprechenden Server anfordert:
#!/usr/local/bin/perl -w
# gethttp.pl -- gets a url

use Socket;

$url = shift;     # get the url from @ARGV
if ($url !~ m!http://(.+?)/(.*)!) {
    die "usage: $0 http://your.host/path/to/url\n";
}

$hostname = $1;
$path     = "/$2";

# we ignore the "host:port" notation, and assume http=80 everytime.
# see Sockets for more details

socket(SOCK, PF_INET, SOCK_STREAM, getprotobyname('tcp'))
    or die "socket(): $!\n";
$paddr = sockaddr_in(80, inet_aton($hostname));
connect(SOCK, $paddr)
    or die "connect(): $!\n";
select (SOCK); $| = 1; # unbuffer i/o

# send the HTTP-Request
print SOCK "GET $path HTTP/1.0\n\n";

# now read the entire response:
$buf = $totbuf = "";
while (read(SOCK, $buf, 1)) {
    $totbuf .= $buf;
}

# $totbuf must be stripped off the HTTP-Header
$posentity = index($totbuf, "\r\n\r\n") + 4;
$totbuf = substr($totbuf, $posentity, length($totbuf)-$posentity);

# print the $totbuf to STDOUT
syswrite(STDOUT, $totbuf, length($totbuf));

close(SOCK);   # it is already closed by server anyway (really ?)

Weitere Informationen

Ein gutes Buch mit Web-Clients ist:

Clinton Wong: Web Client Programming with Perl bei O'Reilly.

Vorherige Seite, Nächster Index Index, Hauptindex.


Copyright © 1997/08/16 by Farid Hajji.