Skip to content

Instantly share code, notes, and snippets.

@preaction
Last active December 10, 2015 22:22
Show Gist options
  • Save preaction/a6736b06a079090d4ecd to your computer and use it in GitHub Desktop.
Save preaction/a6736b06a079090d4ecd to your computer and use it in GitHub Desktop.
use Mojolicious::Lite;
use Mojo::IOLoop;
use Mojo::IOLoop::Stream;
websocket '/' => sub {
my ( $c ) = @_;
my ( $stream, $id );
$c->on( message => sub {
my ( $c, $msg ) = @_;
if ( $stream ) {
$stream->close;
undef $stream;
}
$c->app->log->info( "Got command: $msg" );
if ( open my $fh, '-|', $msg ) {
my $stream = Mojo::IOLoop::Stream->new( $fh );
$stream->on( read => sub {
my ( $stream, $bytes ) = @_;
$c->app->log->debug( "Sending output: $bytes" );
$c->send( $bytes );
} );
$id = Mojo::IOLoop->singleton->stream( $stream );
$c->on( finish => sub {
my ( $c ) = @_;
$c->app->log->debug( "Closing stream" );
undef $stream;
# Either of these two lines makes the app freeze
#Mojo::IOLoop->singleton->remove( $id );
#$stream->close;
} );
}
else {
$c->send( "Could not execute '$msg': $!" );
}
} );
};
app->start;
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment