1 |
joko |
1.1 |
#!/usr/bin/perl |
2 |
|
|
|
3 |
|
|
#use warnings; |
4 |
|
|
#use strict; |
5 |
|
|
|
6 |
|
|
use POE; |
7 |
|
|
use POE::Filter::Reference; |
8 |
|
|
use POE::Component::Server::TCP; |
9 |
|
|
#use POE::Component::Client::TCP; |
10 |
|
|
use Data::Dumper; |
11 |
|
|
|
12 |
|
|
### Create a server that receives and sends Perl data structures. It |
13 |
|
|
### will be referred to by the name "sum-server" when necessary. It |
14 |
|
|
### listens on localhost port 12345. It uses POE::Filter::Reference |
15 |
|
|
### to parse input and format output. |
16 |
|
|
|
17 |
|
|
POE::Component::Server::TCP->new |
18 |
|
|
( Alias => "sum_server", |
19 |
|
|
Address => "localhost", |
20 |
|
|
Port => 12345, |
21 |
|
|
ClientFilter => "POE::Filter::Reference", |
22 |
|
|
|
23 |
|
|
# Handle client requests here. |
24 |
|
|
|
25 |
|
|
ClientInput => sub { |
26 |
|
|
my ( $heap, $list ) = @_[ HEAP, ARG0 ]; |
27 |
|
|
my $sum = 0; |
28 |
|
|
my ( @odd, @even, @bad, $status ); |
29 |
|
|
|
30 |
|
|
print Dumper ($list); |
31 |
|
|
|
32 |
|
|
# Process the request into buckets for odd, even, and |
33 |
|
|
# non-integers. Sum the integers in the request. |
34 |
|
|
|
35 |
|
|
if ( ref($list) eq 'ARRAY' ) { |
36 |
|
|
foreach (@$list) { |
37 |
|
|
if (/^\d+$/) { |
38 |
|
|
if ( $_ % 2 ) { push @odd, $_; } |
39 |
|
|
else { push @even, $_; } |
40 |
|
|
$sum += $_; |
41 |
|
|
} |
42 |
|
|
else { |
43 |
|
|
push @bad, $_; |
44 |
|
|
} |
45 |
|
|
} |
46 |
|
|
$status = "OK"; |
47 |
|
|
} |
48 |
|
|
else { |
49 |
|
|
$status = "Error: Bad request type: " . ref($list); |
50 |
|
|
} |
51 |
|
|
|
52 |
|
|
# Build the response hash, then send it to the client. |
53 |
|
|
|
54 |
|
|
my %response = |
55 |
|
|
( sum => $sum, |
56 |
|
|
odd => \@odd, |
57 |
|
|
even => \@even, |
58 |
|
|
bad => \@bad, |
59 |
|
|
stat => $status, |
60 |
|
|
); |
61 |
|
|
|
62 |
|
|
$heap->{client}->put( \%response ); |
63 |
|
|
}, |
64 |
|
|
|
65 |
|
|
# Since this is a one-shot test program, shut down the server |
66 |
|
|
# after the first client has disconnected. This posts "shutdown" |
67 |
|
|
# to the server itself. Using yield() here would just shut down |
68 |
|
|
# the client connection. |
69 |
|
|
|
70 |
|
|
ClientDisconnected => sub { |
71 |
|
|
my $kernel = $_[KERNEL]; |
72 |
|
|
$kernel->post( sum_server => "shutdown" ); |
73 |
|
|
}, |
74 |
|
|
); |
75 |
|
|
|
76 |
|
|
|
77 |
|
|
### Run both the client and server. Yes, in the same program. |
78 |
|
|
|
79 |
|
|
$poe_kernel->run(); |