Skip to content

Instantly share code, notes, and snippets.

@EatMoreCode
Last active September 3, 2015 02:12
Show Gist options
  • Save EatMoreCode/c492908db38f574985d1 to your computer and use it in GitHub Desktop.
Save EatMoreCode/c492908db38f574985d1 to your computer and use it in GitHub Desktop.
Websocket command line tool. Connects a websocket endpoint with STDIN/STDOUT.
#!/usr/bin/env perl
use Mojo::UserAgent;
use IO::Select;
use feature 'say';
my $ua = Mojo::UserAgent->new();
my $ep = shift;
my $s = IO::Select->new();
$s->add(\*STDIN);
$ua->websocket($ep => sub {
my ($ua, $tx) = @_;
say 'WebSocket handshake failed!' and return unless $tx->is_websocket;
$tx->on(message => sub {
my ($tx, $message) = @_;
say $message;
});
Mojo::IOLoop->recurring(.1 => sub {
my $loop = shift;
if ($s->can_read(.1)) {
my $in = <STDIN>; chomp $in;
$tx->send($in);
}
});
});
Mojo::IOLoop->start unless Mojo::IOLoop->is_running;
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment