IO-Events

 view release on metacpan or  search on metacpan

Events.pm  view on Meta::CPAN

	my $self = $_[0];
	return if $self-> {dead};
	@{$self-> {owner}-> {timers}} = grep { $_ != $self } @{$self-> {owner}-> {timers}};
}

sub start
{
	my $self = $_[0];
	$self-> {alert} = time + $self-> {timeout};
	$self-> {active} = 1;
}

sub stop { $_[0]-> {active} = 0 }

sub active 
{
	my ( $self, $active) = @_;
	return if $active == $self-> {active}; # to avoid restarts
	$active ? $self-> start : $self-> stop;
}

sub notify
{
	my $self = $_[0];

	if ( $self-> {repetitive}) {
		my $time = time;
		# eat up late events
		$self-> {alert} += $self-> {timeout} while $self-> {alert} < $time;
	} else {
		$self-> {active} = 0;
	}
	
	$self-> {event_flag} = 0;
	if ( defined $self->{on_tick}) {
		$self->{on_tick}->($self);
		return if $self->{event_flag};
	}
	$self-> on_tick() if $self-> can('on_tick');
}


1;

__DATA__

=pod

=head1 NAME

IO::Events - Non-blocking IO using events 

=head1 SYNOPSIS

Example 1, run 'bc' as a co-process:

	use IO::Events;

	my $loop = IO::Events::Loop-> new();

	my $stdin_alive = 1;
	my $calculator = IO::Events::Process::ReadWrite-> new(
		owner    => $loop,
		process  => 'bc -l', 
		on_read  => sub {
			while ( my $line = $_[0]-> readline) {
				print "bc says: $line";
			}
		},
		on_close => sub {
			exit 1 if $stdin_alive; # fork/exec error
		}
	);

	my $stdin = IO::Events::stdin-> new(
		owner => $loop,
		on_read => sub { 
		$calculator-> write( $_[0]-> read );
		},
		on_close => sub {
			$stdin_alive = 0;
			exit;
		},
	);

	$loop-> yield while 1;


Example 2, connect to/listen on a TCP port within a single process:

	use IO::Events;
	
	my $loop = IO::Events::Loop-> new();
	IO::Events::Socket::TCP-> new(
		owner    => $loop,
		listen   => 1,
		port     => 10000,
		on_read => sub {
			my $new = shift-> accept( 
				read   => 1,
				on_read => sub {
					while ( my $line = $_[0]-> readline) {
						print "client says: $line\n";
						exit;
					}
				}
			);
	                print "connect from $new->{remote_addr}:$new->{remote_port}\n";
		},
	);
	
	IO::Events::Socket::TCP-> new(
		owner   => $loop,
		connect => 'localhost',
		port 	=> 10000,
	)-> write("hello, tcp socket!\n");
	
	$loop->yield while 1;

Example 3, connect to/listen on a UDP port within a single process:

	use Socket;
	use IO::Events;
	
	my $loop = IO::Events::Loop-> new();
	IO::Events::Socket::UDP-> new(
		owner    => $loop,
		port     => 10000,
		on_read => sub {
			my $self = $_[0];
			my $data = $self-> recv;
			print "$self->{remote_host}:$self->{remote_port} says: $data";
			exit;
		},
	);
	
	IO::Events::Socket::UDP-> new(
		owner   => $loop,
	)-> send( 'localhost', 10000, "hello, udp socket!\n");
	
	$loop->yield while 1;



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