use Protocol::WebSocket::Client;
use AnyEvent;
use AnyEvent::Socket;
use AnyEvent::Handle;

my $cv = AE::cv;
my $client =
  Protocol::WebSocket::Client->new( url => 'ws://localhost:5000/ws' );

$cv->begin;
tcp_connect $client->url->host, $client->url->port, sub {
    my ($fh) = @_ or return $cv->send("Connect failed: $!");

    my $ws_handle = AnyEvent::Handle->new(
        fh      => $fh,
        on_eof  => sub { $cv->end },
        on_read => sub {
            my ($handle) = @_;

            my $buf = delete $handle->{rbuf};
            $client->read($buf);
        },
    );

    $client->on(
        write => sub {
            my ( $client, $buf ) = @_;
            $ws_handle->push_write($buf);
        }
    );
    $client->on(
        read => sub {
            my ( $client, $buf ) = @_;

            if ( $client->{frame_buffer}->is_close ) {
                print "\nclose ", join ",", unpack "B8B8a*", $buf;
                print "\nclose ", join ",", unpack "na*",    $buf;
                print "\n";
            }
        }
    );

    $client->connect;
};
$cv->wait;
