お昼ごはんはゲームです

ゲーム記事やカードゲームのデッキ紹介記事を投稿します。

チャットアプリを作ってみる

WEBアプリを作成したくなったので試しにチャットアプリを作成します。

参考:

kumatetsublog.com

 

まず初めにNode.jsとnpmをインストールします。

Node.jsとは、サーバーサイドのJavaScript実行環境とのことです。

npmはNode Package Managerの略で、JavaScript系のパッケージを管理するツールを言います。

Windows10で作成するため、以下を参考にしました。

これにより準備が完了しました。

qiita.com

 

次にnmpを使ってチャットアプリを作る上で必要となるパッケージをインストールします。

作業用のフォルダでコマンドプロンプトで以下の通りコマンドを実行します。

  • mkdir sample-chat-app (sample-chat-appという名のフォルダを作成)
  • cd sample-chat-app (sample-chat-appへ移動)
  • npm init (npmのインストールのための初期設定)
  • npm install -s express socket.io (expressとsocket.ioをインストール)
  • copy nul index.js (index.jsという名の空ファイルを作成)
  • copy nul chat.html (chat.htmlという名の空ファイルを作成)

各々の説明は以下の通りです。

Webアプリ向けのフレームワーク(express)

サーバーとクライアントとの双方向通信のパッケージ(socket.io)

クライアント側の実装(chat.html)
サーバー側の実装(index.js)

 

ここからはindex.jsとchat.htmlにコードを書きます。

index.js

// パッケージ群を読み込む
var app = require('express')();
var http = require('http').Server(app);
var io = require('socket.io')(http);
// ポート番号を指定する
var port = process.env.PORT || 3000;

// クライアント側のリクエストに対して、画面(htmlファイル)を返す
app.get('/', function(req, res){
res.sendFile(__dirname + '/chat.html');
});

// httpサーバーを立てる
http.listen(port, function(){
console.log('listening on *:' + port);
});

var messages = ;

io.on('connection', function(socket){

// サーバー側のメッセージリストをクライアント側に送る(emit)
socket.emit('init-chat', messages);
// クライアント側から送られたメッセージを受け取り、全クライアントに送る(emit)
socket.on('c2s-msg', function(msg) {
var newMessage = msg;
messages.push(newMessage);
io.emit('s2c-msg', newMessage);
});

});

chat.html

<!DOCTYPE html><!DOCTYPE html><html lang="en" dir="ltr">  <head>    <meta charset="utf-8">    <title>sample-chat-app</title>    <style>      * { margin: 0; padding: 0; box-sizing: border-box; }      body { font: 16px Helvetica, Arial; }      h2 {padding: 10px}      .form { background: #001; padding: 3px; position: fixed; bottom: 0; width: 100%; }      .form input { border: 0; padding: 10px; width: 90%; margin-right: .5%; }      .form button { width: 9%; background: rgb(130, 224, 255); border: none; padding: 10px; }      ul { list-style-type: none; margin: 0; padding: 0; }      ul li { padding: 5px 10px; }      ul { margin-bottom: 10px }    </style>    <script src="https://cdn.jsdelivr.net/npm/vue/dist/vue.js"></script>    <script src="/socket.io/socket.io.js"></script>  </head>  <body>    <header>      <h2>サンプルチャットアプリ</h2>    </header>    <hr>    <main id="chat">      <ul v-for="message in messages">        <li>{{message}}</li>      </ul>      <div class="form">        <input v-model="chatMessage">        <button v-on:click="postMessage">送信</button>      </div>    </main>  </body>  <script>    var socket = io();    var app = new Vue({      el: '#chat',      data: {        chatMessage: '',        messages:       },      methods: {        // 送信ボタンが押されたら、クライアントからサーバーにメッセージを送信    postMessage: function() {          socket.emit('c2s-msg', this.chatMessage);          this.chatMessage = '';          return false;        }
      },    })    // サーバーがメッセージをemitしたら、クライアント側のリストにメッセージを追加する    socket.on('s2c-msg', function(msg) {      console.log(msg);      app.messages.push(msg);      window.scrollTo(0, document.body.scrollHeight);    });
    // 元々あるメッセージを表示する    socket.on('init-chat', function(messages) {      app.messages = messages;    });
  </script></html>

実行方法

コマンドプロンプトで以下のコマンドからサーバーを起動する。

    node index.js

以下のリンクからページを表示する。

http://localhost:3000/

f:id:purin_nau:20210728230815p:plain

 

サーバーを停止する時はコマンドプロンプトでCTRL+Cを押します。

以上。