| 1 |
use strict; |
| 2 |
use warnings; |
| 3 |
use AnyEvent; |
| 4 |
use AnyEvent::Socket; |
| 5 |
use AnyEvent::Handle; |
| 6 |
|
| 7 |
use Protocol::HTTP2::Client; |
| 8 |
use Protocol::HTTP2::Constants qw(const_name); |
| 9 |
|
| 10 |
my $client = Protocol::HTTP2::Client->new( |
| 11 |
on_change_state => sub { |
| 12 |
my ( $stream_id, $previous_state, $current_state ) = @_; |
| 13 |
printf "Stream %i changed state from %s to %s\n", |
| 14 |
$stream_id, const_name( "states", $previous_state ), |
| 15 |
const_name( "states", $current_state ); |
| 16 |
}, |
| 17 |
on_error => sub { |
| 18 |
my $error = shift; |
| 19 |
printf "Error occurred: %s\n", const_name( "errors", $error ); |
| 20 |
}, |
| 21 |
|
| 22 |
# Perform HTTP/1.1 Upgrade |
| 23 |
upgrade => 1, |
| 24 |
); |
| 25 |
|
| 26 |
my $host = '127.0.0.1'; |
| 27 |
my $port = 8000; |
| 28 |
|
| 29 |
# Prepare http/2 request |
| 30 |
$client->request( |
| 31 |
':scheme' => "http", |
| 32 |
':authority' => $host . ":" . $port, |
| 33 |
':path' => "/minil.toml", |
| 34 |
':method' => "GET", |
| 35 |
headers => [ |
| 36 |
'accept' => '*/*', |
| 37 |
'user-agent' => 'perl-Protocol-HTTP2/0.01', |
| 38 |
], |
| 39 |
on_done => sub { |
| 40 |
my ( $headers, $data ) = @_; |
| 41 |
printf "Get headers. Count: %i\n", scalar(@$headers) / 2; |
| 42 |
printf "Get data. Length: %i\n", length($data); |
| 43 |
print $data; |
| 44 |
}, |
| 45 |
); |
| 46 |
|
| 47 |
my $w = AnyEvent->condvar; |
| 48 |
|
| 49 |
tcp_connect $host, $port, sub { |
| 50 |
my ($fh) = @_ or die "connection failed: $!"; |
| 51 |
my $handle; |
| 52 |
$handle = AnyEvent::Handle->new( |
| 53 |
fh => $fh, |
| 54 |
autocork => 1, |
| 55 |
on_error => sub { |
| 56 |
$_[0]->destroy; |
| 57 |
print "connection error\n"; |
| 58 |
$w->send; |
| 59 |
}, |
| 60 |
on_eof => sub { |
| 61 |
$handle->destroy; |
| 62 |
$w->send; |
| 63 |
} |
| 64 |
); |
| 65 |
|
| 66 |
# First write preface to peer |
| 67 |
while ( my $frame = $client->next_frame ) { |
| 68 |
$handle->push_write($frame); |
| 69 |
} |
| 70 |
|
| 71 |
$handle->on_read( |
| 72 |
sub { |
| 73 |
my $handle = shift; |
| 74 |
|
| 75 |
$client->feed( $handle->{rbuf} ); |
| 76 |
|
| 77 |
$handle->{rbuf} = undef; |
| 78 |
while ( my $frame = $client->next_frame ) { |
| 79 |
$handle->push_write($frame); |
| 80 |
} |
| 81 |
$handle->push_shutdown if $client->shutdown; |
| 82 |
} |
| 83 |
); |
| 84 |
}; |
| 85 |
|
| 86 |
$w->recv; |
| 87 |
|