On Jan 30, 2013, at 09:49, Antti Linno wrote:
> 
> 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.

> Any hints, second opinion(maybe not to merge TCP and UDP), or code examples
> are welcome :)


I've attached a working version of your sample code.  It starts two TCP servers 
and a UDP service, and lets them all run at once in the same process.

-- 
Rocco Caputo <[email protected]>

#!/usr/bin/env perl

use warnings;
use strict;

use Socket qw(unpack_sockaddr_in inet_ntoa);
use POE qw(Component::Server::TCP);

sub setup_tcp_server {
	my ($port, $alias) = @_;

	POE::Component::Server::TCP->new(
		Alias       => $alias,
		Port        => $port,
		ClientInput => sub {
			my ($session, $heap, $input) = @_[SESSION, HEAP, ARG0];
			print "Server [$alias] Session ", $session->ID(), " got input: $input\n";
			$heap->{client}->put($input);
		}
	);
}

sub setup_udp_service {
	my ($port, $alias) = @_;

	POE::Session->create(
		inline_states => {
			_start => sub {
				my $socket = IO::Socket::INET->new(
					Proto     => 'udp',
					LocalPort => $port,
				);
				die "Couldn't create server socket: $!" unless $socket;
				$_[KERNEL]->select_read($socket, "get_datagram");
				$_[KERNEL]->alias_set($alias);
			},
			get_datagram => sub {
				my ($kernel, $socket) = @_[KERNEL, ARG0];
				my $remote_address = recv($socket, my $message = "", 65536, 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: $!";
			},
		}
	);
}

setup_tcp_server(11211, "tcp_server_one");
setup_tcp_server(11212, "tcp_server_two");
setup_udp_service(8675, "udp_service_three");

# The imporant part is not to start things until they are set up.
# run() will run the event loop until all work is done.  In this case,
# until all previously setup services shut down---"forever" in the
# example.

POE::Kernel->run();
exit;

Reply via email to