Skip to content

Instantly share code, notes, and snippets.

@Code-Hex
Created June 22, 2015 16:02
Show Gist options
  • Save Code-Hex/25f8d389b2fc3e4c3a53 to your computer and use it in GitHub Desktop.
Save Code-Hex/25f8d389b2fc3e4c3a53 to your computer and use it in GitHub Desktop.
mojolicious + websocket
#!/usr/bin/env perl
use utf8;
use Mojolicious::Lite;
use DateTime;
use Mojo::JSON qw/decode_json encode_json/;
use Encode qw/from_to decode_utf8 encode_utf8/;
use Data::Dumper qw/Dumper/;
get '/' => sub {
my $self = shift;
} => 'index';
my $clients = {};
websocket '/echo' => sub {
my $self = shift;
app->log->debug(sprintf 'Client connected: %s', $self->tx);
my $id = sprintf "%s", $self->tx;
app->log->debug("id:".$id);
$clients->{$id} = $self->tx;
$self->on(message => sub {
my ($self, $msg) = @_;
my ($name,$message) = split(/\t/,$msg);
$self->app->log->debug('name: ', $name, 'message: ', $message);
$name = '名無し' unless($name);
my $dt = DateTime->now( time_zone => 'Asia/Tokyo');
for (keys %$clients) {
$self->app->log->debug('clients', Dumper $clients->{$_});
$clients->{$_}->send(
decode_utf8(encode_json({
hms => $dt->hms,
name => $name,
text => $message,
}))
);
}
}
);
$self->on(finish => sub {
app->log->debug('Client disconnected');
delete $clients->{$id};
}
);
};
app->start;
__DATA__
@@ index.html.ep
% layout 'main';
%= javascript begin
jQuery(function($) {
$('#msg').focus();
var log = function (text) {
$('#log').val( $('#log').val() + text + "\n");
};
var ws = new WebSocket('ws://localhost:3000/echo');
ws.onopen = function () {
log('Connection opened');
};
ws.onmessage = function (msg) {
var res = JSON.parse(msg.data);
log('[' + res.hms + '] (' + res.name + ') ' + res.text);
};
$('#msg').keydown(function (e) {
if (e.keyCode == 13 && $('#msg').val()) {
ws.send($('#name').val() + "\t" + $('#msg').val());
$('#msg').val('');
}
});
});
% end
<h1>Mojolicious + WebSocket</h1>
<p>name<input type="text" id="name" />msg<input type="text" id="msg" /></p>
<textarea id="log" readonly></textarea>
<div>
</div>
@@ layouts/main.html.ep
<html>
<head>
<meta charset="<%= app->renderer->encoding %>">
<title>WebSocket Client</title>
%= javascript 'https://ajax.googleapis.com/ajax/libs/jquery/1.7/jquery.min.js'
<style type="text/css">
textarea {
width: 40em;
height:10em;
}
</style>
</head>
<body><%= content %></body>
</html>
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment