ViewVC Help
View File | Revision Log | Show Annotations | Download File
/cvs/AnyEvent-MP/eg/chat_client
Revision: 1.3
Committed: Fri Aug 7 09:07:37 2009 UTC (14 years, 10 months ago) by elmex
Branch: MAIN
CVS Tags: rel-0_6
Changes since 1.2: +4 -0 lines
Log Message:
changed chat client/server example to the new initialise api and added monitor.

File Contents

# User Rev Content
1 root 1.2 #!/opt/bin/perl
2    
3 elmex 1.1 use AnyEvent;
4     use AnyEvent::Handle;
5     use AnyEvent::MP;
6    
7 root 1.2 my $server_node = "127.0.0.1:1299";
8 elmex 1.1
9 elmex 1.3 initialise_node "slave/", $server_node;
10    
11     print "initialized client\n";
12    
13 root 1.2 my $client_port = port;
14 elmex 1.1
15 root 1.2 snd $server_node, lookup => "chatter", $client_port, "resolved";
16 elmex 1.1
17 root 1.2 my $resolved_cv = AnyEvent->condvar;
18 elmex 1.1 my $server_port;
19    
20     # setup a receiver callback for the 'resolved' message:
21 root 1.2 rcv $client_port, resolved => sub {
22     my ($tag, $chatter_port_id) = @_;
23 elmex 1.1
24     print "Resolved the server port 'chatter' to $chatter_port_id\n";
25     $server_port = $chatter_port_id;
26    
27     $resolved_cv->send;
28     1
29 root 1.2 };
30 elmex 1.1
31 root 1.2 # lets block the client until we have resolved the server port.
32 elmex 1.1 $resolved_cv->recv;
33    
34     # now setup another receiver callback for the chat messages:
35 root 1.2 rcv $client_port, message => sub {
36     my ($tag, $msg) = @_;
37 elmex 1.1
38     print "chat> $msg\n";
39     0
40 root 1.2 };
41 elmex 1.1
42 root 1.2 # send a 'join' message to the server:
43 elmex 1.1 snd $server_port, join => "$client_port";
44    
45     sub send_message {
46     my ($msg) = @_;
47    
48     snd $server_port, message => $msg;
49     }
50    
51     # make an AnyEvent condition variable for the 'quit' condition
52     # (when we want to exit the client).
53     my $quit_cv = AnyEvent->condvar;
54    
55     my $stdin_hdl = AnyEvent::Handle->new (
56 root 1.2 fh => *STDIN,
57     on_error => sub { $quit_cv->send },
58     on_read => sub {
59 elmex 1.1 my ($hdl) = @_;
60    
61     $hdl->push_read (line => sub {
62     my ($hdl, $line) = @_;
63    
64     if ($line =~ /^\/quit/) { # /quit will end the client
65     $quit_cv->send;
66     } else {
67     send_message ($line);
68     }
69     });
70     }
71     );
72    
73     $quit_cv->recv;