Last active
June 26, 2016 16:27
-
-
Save lindleyw/581f4a8758373cff5eea97060205fc6b to your computer and use it in GitHub Desktop.
Mojolicious websocket, with responses interleaved between blocking operations
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
Mojolicious::Lite; | |
use Mojo::URL; | |
# Template with browser-side code | |
get '/' => 'index'; | |
# WebSocket echo service | |
websocket '/echo' => sub { | |
my $c = shift; | |
# Opened | |
$c->app->log->debug('WebSocket opened'); | |
# Increase inactivity timeout for connection a bit | |
$c->inactivity_timeout(300); | |
# Incoming message | |
$c->on(message => sub { | |
my ($c, $msg) = @_; | |
$c->delay( | |
sub { | |
my $delay = shift; | |
print "LOADING $msg\n"; | |
$c->send("Loading n-dimensional geometries." => $delay->begin); | |
$delay->pass(); | |
}, | |
sub { | |
my ($delay, @args) = @_; | |
sleep(1); | |
$delay->pass(@args); | |
}, | |
sub { | |
my ($delay, @args) = @_; | |
$c->send("Calculating Traveling Salesman Problem." => $delay->begin); | |
$delay->pass(@args); | |
}, | |
sub { | |
my ($delay, @args) = @_; | |
sleep(1); | |
$delay->pass(@args); | |
}, | |
sub { | |
my ($delay, @args) = @_; | |
$c->send("You can't get there from here." => $delay->begin); | |
} | |
); | |
# Closed | |
$c->on(finish => sub { | |
my ($c, $code, $reason) = @_; | |
$c->app->log->debug("WebSocket closed with status $code"); | |
}); | |
}; | |
app->start; | |
__DATA__ | |
@@ index.html.ep | |
<!DOCTYPE html> | |
<html> | |
<head><title>Echo</title></head> | |
<body> | |
<script> | |
var ws = new WebSocket('<%= url_for('echo')->to_abs %>'); | |
// Incoming messages | |
ws.onmessage = function (event) { | |
document.body.innerHTML += event.data + '<br/>'; | |
}; | |
// Outgoing messages | |
ws.onopen = function (event) { | |
window.setInterval(function () { ws.send('Hello Mojo!') }, 6000); | |
}; | |
</script> | |
</body> | |
</html> |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment