otherDemo.pl
#!/usr/bin/perl
use strict;
use warnings FATAL => qw(all);
use Sloop::Client::Request;
use Sloop::Logger::SimpleColor;
use Sloop::Other::Regular;
use Sloop::Server;
my $SLOOP_PORT = 8181;
my $OTHER_PORT = 8282;
my $pid = fork;
if (!defined $pid) {
print "Fork failed: $!\n";
exit 1;
}
if (!$pid) {
my $sloop = Sloop::Server->new (
logger => Sloop::Logger::SimpleColor->new('yellow'),
port => $OTHER_PORT
);
die if !$sloop;
$sloop->{handlers} = {
'/' => sub {
my $client = shift;
$client->reply(\"Hello");
},
stop => sub {
my $client = shift;
$client->reply(\"ok");
$client->setAfterReplyHandler(sub { exit 0 });
}
};
$sloop->{logger}->out(2, "Background server starting...\n");
$sloop->run;
} else {
my $sloop = Sloop::Server->new (
logger => Sloop::Logger::SimpleColor->new('cyan'),
port => $SLOOP_PORT
);
die if !$sloop;
my $other = Sloop::Other::Regular->new (
dest_addr => '127.0.0.1',
dest_port => $OTHER_PORT,
incoming => [],
logger => $sloop->{logger}
);
$sloop->connectOther($other);
$sloop->{handlers} = {
'/' => sub {
my $client = shift;
push @{$other->{incoming}}, sub {
my ($self, $raw) = (shift, shift);
my $msg = "";
if ($self->{_data}) {
$msg = $self->{_data};
$self->{_data} = undef;
}
$msg .= $$raw;
$msg = substr($msg, index($msg, "\r\n") + 2);
my $ref = \$msg;
my $headers = Sloop::Client::Request::getHeaders($ref);
my $length = $headers->{'content-length'};
if ($length > length($msg)) {
$self->{_data} = substr($$ref, $length);
$msg = substr($$ref, 0 , 5);
} else { $msg = $$ref }
$client->reply(\"<h2>$headers->{server} said '$msg'.");
return 1;
};
$other->message(\"GET / HTTP/1.1\r\n\r\n");
},
stop => sub {
my $client = shift;
push @{$other->{incoming}}, sub {
$client->reply(\"<h1>Done.");
$client->setAfterReplyHandler(sub { exit 0 });
};
$other->message(\"GET /stop HTTP/1.1\r\n\r\n");
}
};
$sloop->{logger}->out(2, "Foreground server starting...\n");
$sloop->run;
}