Agent

 view release on metacpan or  search on metacpan

Agent/Transport/TCP.pm  view on Meta::CPAN

	# open a new socket & send the data
	my $con = new IO::Socket::INET(
		Proto => 'tcp',
		Timeout => 1,
                PeerAddr => $addr,
                Reuse => 1
	) or return ();	# use IO::Socket's $!

	for( @msg ) { $con->send( $_ ) or return (); }

	# preserve connection?
	${$args{KeepAlive}}  = $con if (ref $args{KeepAlive} eq 'SCALAR');

	$con->close();
	undef $con;	# paranoia
	1;
}

sub valid_address {
	$_ = shift;
	$_ =~ /(^(\d{1,3}\.){3}\d{1,3})|(^(\w+\.)*\w+)\:\d+$/;
	return $_;
}

##
# OO Stuff
##

sub new {
	my ($class, %args) = @_;
	my $self = {};
	my ($addr, $port);

	# set defaults:
	unless ($args{Address}) {
		$args{Address} = '127.0.0.1:24368';
		$args{Cycle} = 1;
	}

	unless (valid_address($args{Address})) {
		warn "Invalid transport address: $args{Address}!";
		return;
	}
	# split so we can cycle port # if need be...
	($addr, $port) = split(/:/, $args{Address});

	# open a new server socket:
	while (1) {
		last if $self->{Server} = new IO::Socket::INET(
			Proto => 'tcp',
			Listen => 1,
			LocalAddr => $addr . ':' . $port,
			Reuse => 1
		);
		print "Couldn't get connection: $!\n" if ($Debug && $!);
		return unless $args{'Cycle'};	# cycle for a free port?
		$port++;
	}

	$self->{Server}->autoflush();
	bless $self, $class;
}

sub recv {
	my ($self, %args) =  @_;

	my $remote = $self->accept(%args) or return ();

	return $remote->getlines();
}

sub accept {
	my ($self, %args) =  @_;

	$self->{Server}->timeout($args{Timeout}) if $args{Timeout};
	my $remote = $self->{Server}->accept() or return;
	$remote->autoflush();
	my $from = $remote->peerhost . ':' . $remote->peerport;
	print "Connection from $from\n" if $Debug;

	# does the caller want to keep the 'from' variable?
	${$args{From}} = $from if (ref $args{From} eq 'SCALAR');
	return $remote;
}

sub address {
	my ($self, %args) =  @_;
	# use socket calls to obtain info about our server socket
	return ($self->{Server}->sockhost . ':' . $self->{Server}->sockport);
}

sub aliases {
	my ($self, %args) =  @_;

	# use socket calls to get all hostnames for our server
	# cheat for now:
	return [ $self->address ];
}

sub transport {
	my ($self, %args) =  @_;
	return 'TCP';
}

1;


__END__

=head1 NAME

Agent::Transport - the Transportable Agent Perl module

=head1 SYNOPSIS

 use Agent::Transport;

 # for receiving messages:
 $tcp = new Agent::Transport(
 	Medium => 'TCP',
 	Address => '1.2.3.4:1234'



( run in 2.218 seconds using v1.01-cache-2.11-cpan-39bf76dae61 )