3
3

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

More than 5 years have passed since last update.

echo サーバ建設メモ (2日目)

3
Last updated at Posted at 2015-07-05

諸君もしってのとおり Starscream の導入に成功した。
うごいてないけど。

で、次はおそらく echo サーバというものが必要。
送ったデータをそのまま返してくれるやつ。
echo サーバを使って送受信のテストをする。

これについては、最近とても気に入ってる Mojolicious を使う。
Perl のフレームワークですね。これで echo サーバを立てる。

とか書いたけど、実際にはもう echo サーバは立ておわってる。
しかも、何週間か前に。

このブログを参考にしたのは覚えている。

Mojolicious::Lite で WebSocket を使ったチャットを作る(現時点:2012年3月10日で動くコード) - 僕のYak Shavingは終わらない
http://kazuph.hateblo.jp/entry/20120310/1331396492

でも、手元で動いているのはこのコード。

perl
# !/usr/bin/env perl
use utf8;
use Mojolicious::Lite;
use DateTime;

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, $msg) = @_;

        my $dt   = DateTime->now( time_zone => 'Asia/Tokyo');

        for (keys %$clients) {
            $clients->{$_}->send({json => {
                hms  => $dt->hms,
                text => $msg,
            }});
        }
    });

    $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://example.com: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>

上記ブログのコードと若干ちがうんだけど、
他のブログも参考にしたのか、自分で修正したのか覚えてないです。

ごめんなさい。
自分でも出典元が知りたい。

そういうわけで、まず上記コードの接続先を修正する。
そして、Web サーバに UP して下記のようにサーバを起動する。

shell
$ morbo /home/example/public_html/ws_server.pl
Server available at http://127.0.0.1:3000

echo サーバが起動した!

ブラウザで echo サーバの動作テストができる。
うまく動かなかったら Chrome のデベロッパーツールを見るのが楽。
http://example.com:3000/

screenshot.png
こんなふうに表示されて、なんとなくチャットができれば成功です。

おわり。

3
3
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
3
3

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?