1 | #!/opt/bin/perl |
1 | #!/opt/bin/perl |
2 | |
2 | |
3 | use AnyEvent; |
3 | use common::sense; |
4 | use AnyEvent::MP; |
4 | use AnyEvent::MP; |
5 | |
5 | |
6 | initialise_node "127.0.0.1:1299"; |
6 | initialise_node; |
7 | |
7 | |
8 | print "initialized server\n"; |
8 | my %clients; |
9 | |
9 | |
10 | my $chatter_port = port; |
10 | sub msg { |
|
|
11 | print "relaying: $_[0]\n"; |
|
|
12 | snd $_, $_[0] |
|
|
13 | for values %clients; |
|
|
14 | } |
11 | |
15 | |
12 | reg $chatter_port, "chatter"; |
16 | sub client_connect { |
|
|
17 | my ($client, $name) = @_; |
13 | |
18 | |
14 | my %client_ports; |
19 | mon $client; |
|
|
20 | mon $client, sub { |
|
|
21 | delete $clients{$client}; |
|
|
22 | msg "$name (quits, @_)"; |
|
|
23 | }; |
15 | |
24 | |
16 | rcv $chatter_port, |
25 | $clients{$client} = $client; |
17 | join => sub { |
|
|
18 | my ($tag, $client_port) = @_; |
|
|
19 | |
26 | |
20 | print "got new client port: $client_port\n"; |
27 | msg "$name (joins)"; |
21 | $client_ports{$client_port} = 1; |
|
|
22 | |
28 | |
23 | mon $client_port, sub { |
29 | rcv $SELF, sub { |
24 | my (@reason) = @_; |
30 | msg "$name: $_[0]"; |
25 | print "client disconnected: " . join (', ', @reason) . "\n"; |
|
|
26 | delete $client_ports{$client_port} |
|
|
27 | }; |
|
|
28 | |
|
|
29 | 0 |
|
|
30 | }, |
|
|
31 | message => sub { |
|
|
32 | my ($tag, $msg) = @_; |
|
|
33 | |
|
|
34 | print "message> $msg\n"; |
|
|
35 | |
|
|
36 | snd $_, message => $msg |
|
|
37 | for keys %client_ports; |
|
|
38 | |
|
|
39 | 0 |
31 | 0 |
40 | }; |
32 | }; |
|
|
33 | } |
41 | |
34 | |
42 | AnyEvent->condvar->recv; |
35 | warn "server ready.\n"; |
|
|
36 | |
|
|
37 | AE::cv->recv; |