ViewVC Help
View File | Revision Log | Show Annotations | Download File
/cvs/AnyEvent-MP/eg/chat_client
Revision: 1.1
Committed: Mon Aug 3 09:43:15 2009 UTC (14 years, 10 months ago) by elmex
Branch: MAIN
Log Message:
added examples from intro.

File Contents

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