Created
November 27, 2018 17:56
-
-
Save john-/ac496cc2dd1e33adff8cee6438fe6240 to your computer and use it in GitHub Desktop.
Websocket and Subprocess
This file contains 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
#!/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