Commit
This commit does not belong to any branch on this repository, and may belong to a fork outside of the repository.
use a better WebSocket example application
- Loading branch information
Showing
4 changed files
with
37 additions
and
52 deletions.
There are no files selected for viewing
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
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,34 @@ | ||
use Mojolicious::Lite; | ||
use Mojo::EventEmitter; | ||
|
||
helper events => sub { state $events = Mojo::EventEmitter->new }; | ||
|
||
get '/' => 'chat'; | ||
|
||
websocket '/channel' => sub { | ||
my $c = shift; | ||
|
||
$c->inactivity_timeout(3600); | ||
|
||
# Forward messages from the browser | ||
$c->on(message => sub { shift->events->emit(mojochat => shift) }); | ||
|
||
# Forward messages to the browser | ||
my $cb = $c->events->on(mojochat => sub { $c->send(pop) }); | ||
$c->on(finish => sub { shift->events->unsubscribe(mojochat => $cb) }); | ||
}; | ||
|
||
# Minimal single-process WebSocket chat application for browser testing | ||
app->start; | ||
__DATA__ | ||
@@ chat.html.ep | ||
<form onsubmit="sendChat(this.children[0]); return false"><input></form> | ||
<div id="log"></div> | ||
<script> | ||
var ws = new WebSocket('<%= url_for('channel')->to_abs %>'); | ||
ws.onmessage = function (e) { | ||
document.getElementById('log').innerHTML += '<p>' + e.data + '</p>'; | ||
}; | ||
function sendChat(input) { ws.send(input.value); input.value = '' } | ||
</script> |
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
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
This file was deleted.
Oops, something went wrong.