# Ein einfacher TCP-Client zum Abspielen von mp3-Dateien
# Verwendung: $0 URL [Port]

use strict;
use warnings;
use IO::Socket;

use constant TIMEOUT => 5;
my $sock = '';
my $reply = '';
my $content = '';
my $header = '';

my $handler = '/usr/bin/audioplay';                # Abspielprogramm

my $url = shift @ARGV;                             # URL zerlegen
$url=~m/http\:\/\/([^\:^\/]*)(?:\:(\d+))?\/(.*)/;
my $host = $1;
my $port = $2;
$port = 80 unless($port);
my $file = '/'.$3;
print "Retrieving File $file from Host $host:$port\n";

$sock = new IO::Socket::INET(PeerAddr => $host,
			     PeerPort => $port,
			     Proto    => 'tcp', Timeout => TIMEOUT)
    or die "can't connect to $ARGV[0]:$ARGV[1]: $@\n";

print "Requesting $file..\n";
print $sock "GET $file HTTP/1.0\n";
print $sock "Accept: */*\n";
print $sock "User-Agent: webamp 007\n\n";
print "Waiting for reply..\n";
$header = <$sock>;
exit unless($header=~m/200|OK/);                   # Ende bei Fehlermeldung
while($header = <$sock>)                           # Header ueberlesen
  {
  print $header;                                   # headerzeilen ausgeben
  chomp($header);
  last unless($header =~ m/\S/);
  }
open(HANDLER, "|$handler") or die "Cannot pipe input to $handler: $!\n";
print "Redirecting HTTP filestream to $handler..\n";
while(read($sock, $content, 512))
  {
  print HANDLER $content;                          # Perl-Strings sind
  }                                                # "binaerfest"
$sock->close() if defined $sock;                   # bei Windows: binmode!
