Last active
December 9, 2015 08:00
-
-
Save Logioniz/f94921ddc33d6a9b6605 to your computer and use it in GitHub Desktop.
Example how handle many long blocking operation when server asynchronous
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
#!/usr/bin/perl | |
use Mojo::Base -strict; | |
use Mojolicious::Lite; | |
use Mojo::IOLoop; | |
use Mojo::IOLoop::ReadWriteFork; | |
plugin 'Mojolicious::Plugin::ForkCall'; | |
get '/' => sub {shift->render(template => 'index') }; | |
websocket '/ws' => sub { | |
my $c = shift; | |
$c->inactivity_timeout(60 * 10); | |
$c->on(message => sub { | |
my ($c, $msg) = @_; | |
$c->delay( | |
sub { | |
my $d = shift; | |
# first background operation | |
$c->fork_call(sub { | |
my @args = @_; | |
sleep 2; | |
return join ', ', @args; | |
}, ['argument_1', 'argument_2' , 'argument_3'] => $d->begin); | |
}, | |
sub { | |
my ($d, @return) = @_; | |
$c->send($return[0]); | |
# second background operation | |
$c->fork_call(sub { | |
my @args = @_; | |
sleep 2; | |
return join ', ', @args; | |
}, ['argument_4', 'argument_5' , 'argument_6'] => $d->begin); | |
}, | |
sub { | |
my ($d, @return) = @_; | |
$c->send($return[0]); | |
# n-th background operation | |
$c->fork_call(sub { | |
my @args = @_; | |
sleep 2; | |
return join ', ', @args; | |
}, ['argument_7', 'argument_8' , 'argument_9'] => $d->begin); | |
}, | |
sub { | |
my ($d, @return) = @_; | |
$c->send($return[0]); | |
} | |
); | |
}); | |
$c->on(finish => sub { | |
my ($c, $code, $reason) = @_; | |
}); | |
} => 'ws'; | |
app->start; | |
__DATA__ | |
@@ index.html.ep | |
<head> | |
<script src="http://code.jquery.com/jquery-2.1.3.min.js"></script> | |
</head> | |
<body> | |
<script> | |
$(document).ready(function () { | |
function websocket () { | |
var ws = new WebSocket('<%= url_for('ws')->to_abs %>'); | |
ws.onmessage = function(event) { | |
document.body.innerHTML += event.data + '<br/>'; | |
}; | |
ws.onopen = function() { | |
ws.send('Need to begin long blocking operation'); | |
} | |
} | |
websocket(); | |
}); | |
</script> | |
</body> | |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment