| 1 |
#!/usr/bin/env perl |
| 2 |
|
| 3 |
use strict; |
| 4 |
use warnings; |
| 5 |
|
| 6 |
use lib 'lib'; |
| 7 |
|
| 8 |
use Devel::Hexdump (); |
| 9 |
use AnyEvent; |
| 10 |
use AnyEvent::Socket; |
| 11 |
use AnyEvent::Handle; |
| 12 |
use Protocol::WebSocket::Client; |
| 13 |
|
| 14 |
$|++; |
| 15 |
|
| 16 |
sub debug { warn "$_[0]\n" } |
| 17 |
|
| 18 |
sub debug_hex { |
| 19 |
debug('v' x 10); |
| 20 |
debug(Devel::Hexdump::xd($_[0])); |
| 21 |
debug('^' x 10); |
| 22 |
} |
| 23 |
|
| 24 |
my $cv = AnyEvent->condvar; |
| 25 |
|
| 26 |
my ($url, $version) = @ARGV; |
| 27 |
die "Usage: $0 <url> <version>" unless $url; |
| 28 |
|
| 29 |
my $client = Protocol::WebSocket::Client->new(url => $url, version => $version); |
| 30 |
my $ws_handle; |
| 31 |
|
| 32 |
debug("! Using version '$version'"); |
| 33 |
|
| 34 |
debug( |
| 35 |
"! Connecting to '" . $client->url->host . ':' . $client->url->port . "'"); |
| 36 |
my ($host, $port) = ($client->url->host, $client->url->port); |
| 37 |
tcp_connect $host, $port, sub { |
| 38 |
my ($fh) = @_ or return $cv->send("Connect failed: $!"); |
| 39 |
|
| 40 |
debug("! Connected"); |
| 41 |
|
| 42 |
$ws_handle = AnyEvent::Handle->new( |
| 43 |
fh => $fh, |
| 44 |
on_eof => sub { |
| 45 |
debug("! Server disconnected"); |
| 46 |
$cv->send; |
| 47 |
}, |
| 48 |
on_error => sub { |
| 49 |
debug("! Error: " . $_[1]); |
| 50 |
$cv->send; |
| 51 |
}, |
| 52 |
on_read => sub { |
| 53 |
my ($handle) = @_; |
| 54 |
|
| 55 |
my $buf = delete $handle->{rbuf}; |
| 56 |
|
| 57 |
debug("< Reading"); |
| 58 |
debug_hex($buf); |
| 59 |
|
| 60 |
$client->read($buf); |
| 61 |
} |
| 62 |
); |
| 63 |
|
| 64 |
$client->on( |
| 65 |
write => sub { |
| 66 |
my $client = shift; |
| 67 |
my ($buf) = @_; |
| 68 |
|
| 69 |
debug("> Writing"); |
| 70 |
debug_hex($buf); |
| 71 |
|
| 72 |
$ws_handle->push_write($buf); |
| 73 |
} |
| 74 |
); |
| 75 |
$client->on( |
| 76 |
read => sub { |
| 77 |
my $self = shift; |
| 78 |
my ($buf) = @_; |
| 79 |
|
| 80 |
} |
| 81 |
); |
| 82 |
$client->connect; |
| 83 |
}; |
| 84 |
|
| 85 |
my $stdin = AnyEvent::Handle->new( |
| 86 |
fh => \*STDIN, |
| 87 |
on_read => sub { |
| 88 |
my $handle = shift; |
| 89 |
|
| 90 |
my $buf = delete $handle->{rbuf}; |
| 91 |
|
| 92 |
$client->write($buf); |
| 93 |
}, |
| 94 |
on_eof => sub { |
| 95 |
$client->disconnect; |
| 96 |
|
| 97 |
$ws_handle->destroy; |
| 98 |
$cv->send; |
| 99 |
} |
| 100 |
); |
| 101 |
|
| 102 |
$cv->wait; |