Hey all, while running Good Vibes Radio, it became necessary to know the number of listeners on the server. You can use this sub to make a program that rings a bell (though good luck getting the Shoutcast plugin to broadcast it), or display it in a webpage, such as at Good Vibes Cafe. It comes in handy. Just call the sub listeners with the port. You can also of course keep track of total listeners if you have several servers on different ports. Have fun. This works with the Shoutcast server. It assumes you have it on the localmachine i.e. localhost, modify as needed.

use strict; use Net::HTTP; sub listeners { my $port=shift; #print "Initializing port $port\n"; my $http=Net::HTTP->new(Host=>"localhost",PeerPort=>$port); $http->write_request('GET'=>'/7.html', 'User-Agent'=>'Mozilla/5.0'); #print "Reading in the HTML.\n"; my ($code,$mess,%h)=$http->read_response_headers; my $buff; my $n=$http->read_entity_body($buff,1024); die "Cannot read the buffer. $!" unless defined $n; my ($line) = $buff =~ /<body>(.+)<\/body>/; my @sc=split(/,/,$line); return $sc[0]; }

Replies are listed 'Best First'.
Re: A sub to return the number of listeners on a Shoutcast server
by b10m (Vicar) on Jan 02, 2004 at 22:23 UTC
    die "Cannot read the buffer. $!" unless defined $n;

    Although I don't run "Good Vibes Radio", nor have any experience with it, I wouldn't use "die" on an error, since you're in a sub. I'd rather return the error message and if none, the number of listeners. If you'd use this sub routine in some script to generate some HTML, the user would at least get a somewhat decent error. (if of course you do something usefull with the returned error ;))

    Just my €0.02

    --
    b10m
      I wouldn't use "die" on an error, since you're in a sub... the user would at least get a somewhat decent error.

      I'd disagree; since all sorts of other things could go wrong, like problems in Net::HTTP, I'd vote for a "die" and using an eval {} block around it if you want to catch the errors and handle them in some specific way.

      Thanks for your help. Initially the sub just got used in a locally running program, so it didn't matter if it died like that, but if running in a CGI application then it would cause trouble as you point out. Good call.