Skip to content

Instantly share code, notes, and snippets.

@t-kashima
Created September 19, 2011 16:01
Show Gist options
  • Save t-kashima/1226827 to your computer and use it in GitHub Desktop.
Save t-kashima/1226827 to your computer and use it in GitHub Desktop.
#!/usr/bin/env perl
use strict;
use warnings;
use Mojolicious::Lite;
use DateTime;
use Mojo::JSON;
use utf8;
get '/' => 'index';
my $clients = {};
websocket '/echo' => sub {
my $self = shift;
app->log->debug(sprintf 'Client connected: %s', $self->tx);
my $id = sprintf "%s", $self->tx;
$clients->{$id} = $self->tx;
$self->on_message(
sub {
my ($self, $message) = @_;
my $json = Mojo::JSON->new;
my $dt = DateTime->now( time_zone=>'Asia/Tokyo' );
# app->log->debug($message);
for (keys %$clients) {
$clients->{$_}->send_message(
$json->encode({
hms => $dt->hms,
text => $message,
})
);
}
}
);
$self->on_finish(
sub {
app->log->debug('Client disconnected');
delete $clients->{$id};
}
);
};
app->start;
__DATA__
@@ index.html.ep
<html>
<head>
<title>WebSocket Client</title>
%= javascript 'http://ajax.googleapis.com/ajax/libs/jquery/1.4.2/jquery.min.js';
%= javascript '/js/ws.js';
</head>
<body>
<h1>Mojolicious + WebSocket</h1>
<p><input type="text" id="msg" /></p>
<textarea id="log" readonly></textarea>
</body>
</html>
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment