Hello.
I need help in consolidating services. Tried to read documentation, but
didn't understand much. Checked cookbook and found a couple of suitable
examples and as the time was pressing, just started services.
Went with sungo's TCP server and UDP socket recipe. Now I have 3 tcp
programs running and 1 udp. All are standalone daemons.It's time to migrate
them to one executable file.
I can migrate sungo's recipe to the POE::Component::Server::TCP easily(I
think), hence I can create 3 servers in one file, but how do I add UDP
server?
TCP test snippet(skipped some parts):
use POE qw(Component::Server::TCP);
POE::Component::Server::TCP->new(
Alias => "echo_server",
Port => 11211,
ClientInput => sub {
my ($session, $heap, $input) = @_[SESSION, HEAP, ARG0];
print "Server [1] Session ", $session->ID(), " got input: $input\n";
$heap->{client}->put($input);
}
);
POE::Component::Server::TCP->new(
Alias => "echo_server",
Port => 11212,
ClientInput => sub {
my ($session, $heap, $input) = @_[SESSION, HEAP, ARG0];
print "Server [2] Session ", $session->ID(), " got input: $input\n";
$heap->{client}->put($input);
}
);
$poe_kernel->run();
Or I need advice, how to merge several sungo's(
http://poe.perl.org/?POE_Cookbook/TCP_Servers) daemons into one package, if
someone would be so kind. Adding UDP should be fairly similar then.
With UDP part I tried some rookie "throw it together, maybe it works"
stuff, but it didn't :) Tried to use Session->create twice, but the second
session didn't work.
Any hints, second opinion(maybe not to merge TCP and UDP), or code examples
are welcome :)
ATM the barebones of the working UDP service are(took from cookbook,
cleaner and less code, but the gist is same):
POE::Session->create(
inline_states => {
_start => \&server_start,
get_datagram => \&server_read,
});POE::Kernel->run();exit;
sub server_start {
my $kernel = $_[KERNEL];
my $socket = IO::Socket::INET->new(
Proto => 'udp',
LocalPort => '8675',
);
die "Couldn't create server socket: $!" unless $socket;
$kernel->select_read($socket, "get_datagram");}
sub server_read {
my ($kernel, $socket) = @_[KERNEL, ARG0];
my $remote_address = recv($socket, my $message = "", DATAGRAM_MAXLEN, 0);
return unless defined $remote_address;
my ($peer_port, $peer_addr) = unpack_sockaddr_in($remote_address);
my $human_addr = inet_ntoa($peer_addr);
print "(server) $human_addr : $peer_port sent us $message\n";
$message =~ tr[a-zA-Z][n-za-mN-ZA-M];
send($socket, $message, 0, $remote_address) == length($message)
or warn "Trouble sending response: $!";}
Thank you.