in reply to Re: Event based handling of multiple connections with AnyEvent
in thread Event based handling of multiple connections with AnyEvent

You can do better in the server. Let $loop->listen() set up the socket rather than doing it yourself. Also, don't use $newclient->send() as that may block; $self->write() will put data into the Stream's outbound queue to be delivered as normal.
#####################3 server.pl
use strict;
use warnings;
use diagnostics;
use Time::HiRes qw(time);
use IO::Async::Stream;
use IO::Async::Loop;
use Socket qw( SOCK_STREAM );

my $loop = IO::Async::Loop->new();

$loop->listen(
    service   => 8888,
    socktype  => SOCK_STREAM,
    queuesize => 5,
    reuseaddr => 1,

    on_accept => sub {
        my ( $newclient ) = @_;

        $loop->add(
            IO::Async::Stream->new(
                handle => $newclient,

                on_read => sub {
                    my ( $self, $buffref, $closed ) = @_;
                    warn 'READ: ', $$buffref;
                    my $send_start = time;
                    $self->write( 'ECHO: ' . $$buffref );
                    warn 'TIME TO SEND TO CLIENT: ', time - $send_start;
                    $$buffref = '';
                    return 0;
                },
            ),
        );
    },

    on_resolve_error => sub { print STDERR "Cannot resolve - $_[0]\n"; },
    on_listen_error  => sub { print STDERR "Cannot listen\n"; },
);

$loop->loop_forever();
  • Comment on Re^2: Event based handling of multiple connections with AnyEvent