Skip to content

Instantly share code, notes, and snippets.

@Logioniz
Last active August 29, 2015 14:18
Show Gist options
  • Save Logioniz/818e96e8ace979458f00 to your computer and use it in GitHub Desktop.
Save Logioniz/818e96e8ace979458f00 to your computer and use it in GitHub Desktop.
Websocket vs EventSource. Need open in many tabs of browsers to see "Waiting for available socket" for EventSource.
#!/usr/bin/perl
use strict;
use warnings;
use v5.10;
use Mojolicious::Lite;
use Mojo::IOLoop;
get '/' => sub {
my $c = shift;
$c->render(template => 'index');
};
get '/es' => sub {
my $c = shift;
$c->inactivity_timeout(60 * 10);
$c->res->headers->content_type('text/event-stream; charset="UTF-8"');
Mojo::IOLoop->recurring(1 => sub {
state $i = 0;
$c->write("event: es\ndata: $i\n\n");
++$i;
});
} => 'es';
websocket '/ws' => sub {
my $c = shift;
$c->inactivity_timeout(60 * 10);
Mojo::IOLoop->recurring(1 => sub {
state $i = 0;
$c->send("$i");
++$i;
});
$c->on(message => sub {
my ($c, $msg) = @_;
$c->send("echo: $msg");
});
$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 event_source () {
var evtSource = new EventSource("<%= url_for 'es' %>");
evtSource.addEventListener("es", function(e) {
document.body.innerHTML += e.data + '<br/>';
});
}
function websocket () {
var ws = new WebSocket('<%= url_for('ws')->to_abs %>');
ws.onmessage = function(event) {
document.body.innerHTML += event.data + '<br/>';
};
}
event_source();
//websocket();
});
</script>
</body>
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment