Apache-Backend-POE
view release on metacpan or search on metacpan
lib/Apache/Backend/POE/Connection.pm view on Meta::CPAN
package Apache::Backend::POE::Connection;
use warnings;
use strict;
use Apache::Backend::POE::Message;
use IO::Socket::INET;
use POSIX qw(:errno_h);
use Carp qw(croak);
use bytes;
use Storable qw(nfreeze thaw);
sub new {
my $class = shift;
return bless({
@_, # can be a hash
}, $class);
}
sub connect {
my ($obj, $poe, $host, $port) = @_;
my $self = bless({%{$obj}},ref($obj));
$self->{parent} = $poe;
$self->{service_name} = $self->{alias} || 'backend-';
if ($host && $port) {
$self->{host} = $host;
$self->{port} = $port;
}
unless ($self->{host} && $self->{port}) {
croak "Must pass host and port to connect or initial new";
}
# connect
$self->{socket} = IO::Socket::INET->new(
PeerAddr => $self->{host},
PeerPort => $self->{port},
) or do {
#croak "Couldn't connect to $self->{host} : $self->{port} - $!";
print STDERR "$$ Apache::Backend::POE:Connection Couldn't connect to $self->{host} : $self->{port} - $!\n";
return undef;
};
binmode($self->{socket});
#$self->{socket}->autoflush(1); # default
$self->{socket}->blocking(0);
$self->{buffer} = "";
$self->{read_length} = undef;
# register
$self->msg_send($self->msg({
cmd => "register_service",
svc_name => $self->{service_name}.$$,
}));
#$self->msg_read(5);
return $self;
}
sub msg {
my $self = shift;
return Apache::Backend::POE::Message->new(@_);
}
sub ping {
my $self = shift;
my $start = time();
# my $no_pong = 1;
$self->msg_send($self->msg({
cmd => 'ping',
time => time(),
}));
my $prefix = "$$ Apache::Backend::POE:Connection ";
print STDERR "$prefix going to msg_read in ping()\n" if $Apache::Backend::POE::DEBUG > 1;
my $msg = $self->msg_read(10);
print STDERR "$prefix back from msg_read in ping()\n" if $Apache::Backend::POE::DEBUG > 1;
unless (ref($msg)) {
print STDERR "$prefix received a non reference\n" if $Apache::Backend::POE::DEBUG;
return -1;
}
if ($Apache::Backend::POE::DEBUG) {
# print STDERR "$prefix got a ".ref($msg)." package with no event()\n",return -99 unless ($msg->can('event'));
}
my $function = $msg->event();
# print STDERR "$prefix function: $function\n";
if ($Apache::Backend::POE::DEBUG) {
print STDERR "$prefix no function in message\n" unless defined $function;
}
return 1 if (defined $function && $function eq 'pong');
print STDERR "$prefix WRONG function received: $function\n" if $Apache::Backend::POE::DEBUG;
return 0;
}
sub disconnect {
my $self = shift;
( run in 1.496 second using v1.01-cache-2.11-cpan-cdf2f3d4e48 )