Net-Curl

 view release on metacpan or  search on metacpan

examples/03-multi-event.pl  view on Meta::CPAN

	# socket callback and register IO events.
	#
	# It _must_ be called _after_ add_handle(); AE will take care
	# of that.
	#
	# We are delaying the call because in some cases socket_action
	# may finish inmediatelly (i.e. there was some error or we used
	# persistent connections and server returned data right away)
	# and it could confuse our application -- it would appear to
	# have finished before it started.
	AE::timer 0, 0, sub {
		$multi->socket_action();
	};

	$multi->SUPER::add_handle( $easy );
}

# perform and call any callbacks that have finished
sub socket_action
{
	my $multi = shift;

	my $active = $multi->SUPER::socket_action( @_ );
	return if $multi->{active} == $active;

	$multi->{active} = $active;

	while ( my ( $msg, $easy, $result ) = $multi->info_read() ) {
		if ( $msg == Net::Curl::Multi::CURLMSG_DONE ) {
			$multi->remove_handle( $easy );
			$easy->finish( $result );
		} else {
			die "I don't know what to do with message $msg.\n";
		}
	}
}

1;

=head2 TEST Easy package

Multi::Event requires Easy object to provide finish() method.

=cut
package Easy::Event;
use strict;
use warnings;
use Net::Curl::Easy qw(/^CURLOPT_/);
use base qw(Net::Curl::Easy);

sub new
{
	my $class = shift;
	my $uri = shift;
	my $cb = shift;

	my $easy = $class->SUPER::new(
		{ uri => $uri, body => '', cb => $cb }
	);
	$easy->setopt( CURLOPT_URL, $uri );
	$easy->setopt( CURLOPT_WRITEHEADER, \$easy->{headers} );
	$easy->setopt( CURLOPT_FILE, \$easy->{body} );

	return $easy;
}

sub finish
{
	my ( $easy, $result ) = @_;

	printf "\nFinished downloading %s: %s: %d bytes\n", 
		$easy->{uri}, $result, length $easy->{body};

	$easy->{cb}->( $easy->{body} );
}

1;

=head2 TEST APPLICATION

	#!perl
	use strict;
	use warnings;
	use Easy::Event;
	use Multi::Event;
#nopod
=cut
package main;
#endnopod
use AnyEvent;

my $multi = Multi::Event->new();
my $cv = AE::cv;


my @uris = (
	"http://www.google.com/search?q=perl",
	"http://www.google.com/search?q=curl",
	"http://www.google.com/search?q=perl+curl",
);


my $i = scalar @uris;
sub done
{
	my $body = shift;

	# process...
	
	unless ( --$i ) {
		$cv->send;
	}
}

my $timer;
$timer = AE::timer 0, 0.1, sub {
	my $uri = shift @uris;
	$multi->add_handle( Easy::Event->new( $uri, \&done ) );

	unless ( @uris ) {
		undef $timer;



( run in 0.521 second using v1.01-cache-2.11-cpan-39bf76dae61 )