#!/usr/bin/perl
# Test configuration: IP, 1/100 simultaneous connections
#   WHAT                            THREADS     SPEED       CPU:
# IO::Stream                        1           2600/sec    60%
# IO::Stream                        100         3100/sec    72%
# POWER::Event::IO                  1           2300/sec    70%
# POWER::Event::IO                  100         2900/sec    75%
use warnings;
use strict;

use Socket;
use Data::Dumper;

use blib;
use EV;
use IO::Stream;

use Carp::Heavy;
$SIG{PIPE}  = 'IGNORE';
$EV::DIED   = \&EV::unloop;

warn "Testing IO::Stream-$IO::Stream::VERSION\n";

sub new_http {
    IO::Stream->new({
        host        => '127.0.0.1',
#        host        => 'localhost',
        port        => $ARGV[0] || 80,
        cb          => \&http,
        wait_for    => EOF,
        out_buf     => "GET http://127.0.0.1/ HTTP/1.0\r\nHost: 127.0.0.1\r\n\r\n",
        in_buf_limit=> 1024000,
    })
};
new_http() for 1 .. 100;

my $RUNS = 0;
my $alarm = 15;

my $t = EV::timer $alarm, 0, sub {
    warn sprintf "RUNS=%d (%d/sec)\n", $RUNS, $RUNS/$alarm;
    EV::unloop;
};
EV::loop;
die "out of loop(): $@\n";

sub http {
    my ($io, $e, $err) = @_;
    die "err=$err\n" if $e != EOF;
#    warn "length = ".length($io->{in_buf})." bytes = $io->{in_bytes}\n";
#    warn $io->{in_buf}; exit;
    warn "bad length: $io->{in_bytes}\n"
        if $io->{in_bytes} != 314;
    $io->close();
    new_http();
    $RUNS++;
}