Created
April 17, 2016 06:03
-
-
Save briandfoy/75e8c06669beca69b3078269438cbed9 to your computer and use it in GitHub Desktop.
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
websocket '/find' => sub ( $c ) { | |
state $loop = Mojo::IOLoop->singleton; | |
app->log->debug( "websocket for find" ); | |
$c->inactivity_timeout( 50 ); | |
my $id; | |
$c->on( message => sub ( $ws, $message ) { | |
my $json = decode_json( $message ); | |
my $command = $json->{c}; | |
my $name = $json->{n}; | |
app->log->debug( "Got $command command for $name" ); | |
if( $command eq "start" ) { | |
$id = run_command( $ws ); | |
app->log->debug( "run_command for $name returned [$id]" ); | |
} | |
elsif( $command eq "stop" ) { | |
app->log->debug( "stopping loop for $name [$id]" ); | |
} | |
elsif( $command eq "open" ) { | |
app->log->debug( "opening websocket for $name" ); | |
} | |
} | |
); | |
$c->on( | |
finish => sub ( $c, $code ) { | |
app->log->debug("WebSocket closed with status $code"); | |
} | |
); | |
}; | |
app->start; | |
sub run_command ( $ws ) { | |
app->log->debug( "In run_command: $ws" ); | |
open my $fh, "$^X -le '\$|++; while(1) { print int rand(100); sleep 3 }' |"; | |
$fh->autoflush; | |
my $id; | |
$id = Mojo::IOLoop->recurring( 1 => sub ($loop) { | |
my $m = <$fh>; | |
unless( defined $m ) { | |
app->log->debug( "Closing down recurring loop from the inside [$id]" ); | |
close $fh; | |
return; | |
}; | |
chomp $m; | |
app->log->debug( "Input [$m] for [$id] from $fh" ); | |
$ws->send( encode_json( { 'm' => $m } ) ); | |
}); | |
return $id; | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment