my$client=Protocol::HTTP2::Client->new(on_change_state=>sub {my($stream_id,$previous_state,$current_state)=@_;printf"Stream %i changed state from %s to %s\n",$stream_id,const_name("states",$previous_state),const_name("states",$current_state);},on_error=>sub {my$error=shift;printf"Error occured: %s\n",const_name("errors",$error);},);
my$w=AnyEvent->condvar;tcp_connect$host,$port,sub {my($fh)=@_ordie"connection failed: $!";my$handle;$handle=AnyEvent::Handle->new(fh=>$fh,autocork=>1,on_error=>sub {$_[0]->destroy;print"connection error\n";$w->send;},on_eof=>sub {$handle->destroy;$w->send;});# First write preface to peerwhile(my$frame=$client->next_frame){$handle->push_write($frame);}$handle->on_read(sub {my$handle=shift;$client->feed($handle->{rbuf});$handle->{rbuf}=undef;while(my$frame=$client->next_frame){$handle->push_write($frame);}$handle->push_shutdownif$client->shutdown;});};$w->recv;
簡単ですね(?)
123456
$ carton exec -- perl client-simple.pl
Stream 1 changed state from IDLE to HALF_CLOSED
Stream 1 changed state from HALF_CLOSED to CLOSED
Get headers. Count: 6
Get data. Length: 14
Hello HTTP/2!
$ carton exec -- perl client-multi-streams.pl
Stream 1 changed state from IDLE to HALF_CLOSED
Stream 3 changed state from IDLE to HALF_CLOSED
Stream 3 changed state from HALF_CLOSED to CLOSED
Get headers. Count: 6
Get data. Length: 14
Hello HTTP/2!
Stream 1 changed state from HALF_CLOSED to CLOSED
Get headers. Count: 6
Get data. Length: 100000000
Finish getting largefile.