çµè«
Herokuã§ã¯ãªããåããªãã£ããã¾ããPerlã§ã¯ãµãã¼ããã¦ããªããã¨ãåé¡ããªï¼
åå ã¯ãããããã©ã¨ããããããã®ã¾ã¾ã«ãã¦ãã
対å¿
app.psgi
# chatã®ç»é¢ get '/chat' => sub { # ãã©ã¡ã¼ã¿ãåå¾ my $self = shift; my $jslist = ['chat.js']; # URL my $url_base = $self->req->url->base; $url_base =~ s/http/ws/g; $self->stash('url_base', $url_base); # å¤æ°ãã»ãã my $sub_title = 'WebScoketã§ãã£ããã®ãã¹ã'; # ãã³ãã¬ã¼ãå¤æ°ãã»ãã $self->stash('title', $config->{title}); $self->stash('description', $config->{description}); $self->stash('github', $config->{github}); $self->stash('subTitle', $sub_title); $self->stash('jsList', $jslist); # chatãã¼ã¸ãå²ãå½ã¦ $self->render('chat'); }; my $clients = {}; # WebSocketã®å¦ç websocket '/echo' => sub { my $self = shift; my $id = sprintf "%s", $self->tx; $clients->{$id} = $self->tx; # $self->receive_message( # ãã使ããªã $self->on(message => sub { my ($self, $msg) = @_; my $json = Mojo::JSON->new; my $dt = DateTime->now( time_zone => 'Asia/Tokyo'); for (keys %$clients) { # $clients->{$_}->send_message( # ãããï¼ $clients->{$_}->send( $json->encode({ hms => $dt->hms, text => $msg, }) ); } } ); # $self->finished( # å¥å $self->on(finish => sub { delete $clients->{$id}; } ); };
chat.html.ep
% layout 'default'; <div class="row-fluid"> <div class="col-12"> <div> <div id="url" style="display: none;"><%= $url_base %></div> <p><input type="text" id="msg" /></p> <textarea id="log" readonly style="width: 500px;height: 250px;"></textarea> </div> </div> </div> </div> ~
chat.js
$(function () { var _url = $("#url").text(); var log = function (text) { $('#log').val( $('#log').val() + text + "\n"); }; var ws = new WebSocket(_url + '/echo'); ws.onopen = function () { log('Connection opened'); }; ws.onmessage = function (msg) { var res = JSON.parse(msg.data); log('[' + res.hms + '] ' + res.text); }; $('#msg').keydown(function (e) { if (e.keyCode == 13 && $('#msg').val()) { ws.send($('#msg').val()); $('#msg').val(''); } }); }); ~
ãªããåãã¦ããæã
ã¾ã¨ã
ãªããå¤é¨ãµã¼ãã§å®é¨ã§ããªããã¨ãããã£ã¦ããæã
ä»ã¯Perlã®å®é¨ãã¦ããããå
¬éã§ããåã¯ãã¨Herokuã§ã§ããç¯å²ã«å¶éãã
ãã®ãã¡ç解ãã¦ããããç°å¢ãå¤ãã¦ã¿ã
è£è¶³
Herokuã§ã¯ãµãã¼ããã¦ããã¿ãã