AnyEventサンプルその6

AnyEvent::JSONRPC::Liteから要点を抜き出す。サーバ内部のcondvarをrecvしている箇所。

サーバ側

use strict;
use warnings;
use AnyEvent;
use AnyEvent::Handle;
use AnyEvent::Socket;
use Data::Dumper;

tcp_server '127.0.0.1', 8888, sub {
    my ($fh) = @_ or die;
    my $handle = AnyEvent::Handle->new(
        fh       => $fh,
        on_error => sub {
            shift->destroy;
            warn "ON ERROR $!";
        },
        on_eof => sub {
            shift->destroy;
            warn "ON EOR $!";
        },
    );

    $handle->on_read(
        sub {
            undef $handle;
            shift->unshift_read(
                line => sub {
                    warn Dumper \@_;
                    my ( $handle, $request ) = @_;
                    my $inner_cv = AE::cv;
                    $inner_cv->cb(
                        sub {
                            my $result = $_[0]->recv;
                            $handle->push_write( $result . "\n" );
                        }
                    );
                    $inner_cv->send( $request . " echo !!" );
                }
            );
        }
    );
};
AE::cv->recv;

クライアント側

use strict;
use warnings;
use AnyEvent;
use AnyEvent::Handle;
use AnyEvent::Socket;
use Data::Dumper;

my $cv = AE::cv;
tcp_connect '127.0.0.1', 8888, sub {
    my ($fh) = @_ or die;
    my $handle = AnyEvent::Handle->new(
        fh       => $fh,
        on_error => sub {
            shift->destroy;
            warn "ON ERROR $!";
        },
        on_eof => sub {

        },
    );
    $handle->push_write("this is testdayo\n");
    $handle->push_read(
        line => sub {
            undef $handle;
            my ( $handle, $line ) = @_;
            $cv->send($line);
        }
    );
};
print $cv->recv;
print "\n"