Skip to content

Instantly share code, notes, and snippets.

@Logioniz
Created April 18, 2016 11:10
Show Gist options
  • Save Logioniz/0c08e4974ab20b190382a429b913d8e6 to your computer and use it in GitHub Desktop.
Save Logioniz/0c08e4974ab20b190382a429b913d8e6 to your computer and use it in GitHub Desktop.
Eample with blocking task.
# to run simple execute: morbo 1.pl
# go to link htpp://127.0.0.1:3000/
use Mojolicious::Lite;
use Mojo::IOLoop;
use Mojo::IOLoop::ReadWriteFork;
get '/' => 'index';
websocket '/find' => sub {
my $c = shift->render_later;
$c->inactivity_timeout(120);
app->log->debug('connect');
my $id;
$c->on(json => sub {
my ($c, $message) = @_;
if($message->{command} eq 'start') {
$c->stash(fork => my $fork = Mojo::IOLoop::ReadWriteFork->new);
$fork->on(read => sub {
my($fork, $buffer) = @_;
$c->send({json => {data => $buffer}});
});
$fork->start(program => 'perl', program_args => ['6.pl']);
} elsif ($message->{command} eq 'stop') {
app->log->debug('stop');
$c->finish;
}
});
$c->on(finish => sub {
my $c = shift;
app->log->debug('finish event');
return unless my $fork = $c->stash('fork');
$fork->kill;
});
};
app->start;
__DATA__
@@ index.html.ep
<body>
<script>
var ws = new WebSocket('<%= url_for('find')->to_abs %>');
ws.onmessage = function (event) {
document.body.innerHTML += event.data + '<br/>';
};
ws.onopen = function (event) {
ws.send(JSON.stringify({command: 'start'}));
};
function stop () {
ws.send(JSON.stringify({command: 'stop'}));
}
</script>
<button onclick="stop()">stop</button><br/>
</body>
#!/usr/bin/perl
$|++;
while(1) {
sleep 3;
print int(rand 200) . "\n";
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment