Mojo::IOLoopを使ってEchoサーバ

Mojo::IOLoopを使ってEchoサーバを書いてみました。

use strict;
use warnings;
use Mojo::IOLoop;

my @_listen;
my %message;


# options                                                                        
my $options = {};
$options->{port} = 3000;

# Accept callback                                                                
$options->{cb} = sub {
    my ($loop, $id) = @_;

    $loop->not_writing($id);

    # Callbacks                                                                  
    $loop->error_cb($id => sub { _error(@_) });
    $loop->hup_cb($id => sub { _hup(@_) });
    $loop->read_cb($id => sub { _read(@_) });
    $loop->write_cb($id => sub { _write(@_) });
};

# Listen                                                                         
my $loop = Mojo::IOLoop->new;
my $id = $loop->listen($options);
push @_listen, $id;

# Start                                                                          
$loop->start;


# Callbacks                                                                      
sub _hup {
    my ($self, $loop, $id) = @_;
    warn "Hup";
}

sub _error {
    my ($loop, $id, $error) = @_;
    warn "$error";
}

sub _read {
    my ($loop, $id, $chunk) = @_;
    $message{$id} = $chunk;
    $loop->writing($id);
}

sub _write {
    my ($loop, $id) = @_;
    my $chunk = $message{$id};
    $loop->not_writing($id);
    return $chunk;
}