Skip to content

Commit

Permalink
use a better WebSocket example application
Browse files Browse the repository at this point in the history
  • Loading branch information
kraih committed Mar 31, 2015
1 parent b4a5e31 commit 3b83c2c
Show file tree
Hide file tree
Showing 4 changed files with 37 additions and 52 deletions.
34 changes: 34 additions & 0 deletions examples/chat.pl
@@ -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>
1 change: 0 additions & 1 deletion examples/connect-proxy.pl
Expand Up @@ -80,7 +80,6 @@
For testing use something like "HTTPS_PROXY=http://127.0.0.1:3000".
EOF

# Start event loop
Mojo::IOLoop->start;

1;
10 changes: 3 additions & 7 deletions examples/microhttpd.pl
@@ -1,7 +1,7 @@
use Mojo::Base -strict;
use Mojo::IOLoop;

# Minimal ioloop example demonstrating how to cheat at HTTP benchmarks :)
# Minimal event loop example demonstrating how to cheat at HTTP benchmarks :)
my %buffer;
Mojo::IOLoop->server(
{port => 8080} => sub {
Expand All @@ -11,13 +11,9 @@
read => sub {
my ($stream, $chunk) = @_;

# Append chunk to buffer
$buffer{$id} .= $chunk;

# Check if we got start-line and headers (no body support)
$buffer{$id} .= $chunk;
if (index($buffer{$id}, "\x0d\x0a\x0d\x0a") >= 0) {

# Clean buffer
delete $buffer{$id};

# Write a minimal HTTP response
Expand All @@ -37,7 +33,7 @@
On a MacBook Air this results in about 18k req/s.
EOF

# Start event loop
# Stop gracefully to make profiling easier
Mojo::IOLoop->recurring(1 => sub { });
local $SIG{INT} = local $SIG{TERM} = sub { Mojo::IOLoop->stop };
Mojo::IOLoop->start;
Expand Down
44 changes: 0 additions & 44 deletions examples/websocket.pl

This file was deleted.

0 comments on commit 3b83c2c

Please sign in to comment.