Skip to content

Instantly share code, notes, and snippets.

@john-
Created November 27, 2018 17:56
Show Gist options
  • Save john-/ac496cc2dd1e33adff8cee6438fe6240 to your computer and use it in GitHub Desktop.
Save john-/ac496cc2dd1e33adff8cee6438fe6240 to your computer and use it in GitHub Desktop.
Websocket and Subprocess
#!/usr/bin/env perl
use Mojolicious::Lite;
use Mojo::IOLoop::Subprocess;
get '/' => sub {
my $c = shift;
$c->render(template => 'index');
};
websocket '/ws' => sub {
my $self = shift;
app->log->debug(sprintf 'Client connected: %s', $self->tx);
$self->on(finish => sub {
app->log->debug('Client disconnected');
});
};
my $count = 0;
Mojo::IOLoop->recurring(3 => sub {
my $loop = shift;
$count++;
app->log->debug(sprintf('Notify %d', $count));
my @args = ( 'echo "hello" > /dev/null' );
my $subprocess = Mojo::IOLoop::Subprocess->new;
$subprocess->run(
sub {
my $subprocess = shift;
system(@args);
return 'hello';
},
sub {
my ($subprocess, $err, @results) = @_;
app->log->error(sprintf('could not do command: %s', $err)) if $err;
}
);
});
app->start;
__DATA__
@@ index.html.ep
% layout 'default';
% title 'Welcome';
<h1>Welcome to the Mojolicious real-time web framework!</h1>
<script>
console.log("Application is running");
var ws = new WebSocket('<%= url_for('ws')->to_abs %>');
ws.onmessage = function(e){
var msg = JSON.parse(e.data);
console.log(msg);
};
</script>
@@ layouts/default.html.ep
<!DOCTYPE html>
<html>
<head><title><%= title %></title></head>
<body><%= content %></body>
</html>
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment