AWSでチャットサービスを公開してみよう! 【EC2 + Express + Socket.io】 前編
ウェイさん
日本酒だいすきエンジニアのウェイさんがお送りします。
みなさんこんにちは、AWSという言葉聞いたことあるでしょうか。
AWSは『Amazon Web Service』の略称で、Amazonが提供するクラウドコンピューティングサービスです。
とにかく色々と出来るサービスですのでAWSでどのようなことが行えるか詳しく知りたい方はこちらの記事がおすすめです。
目標としては一番基本的なサービスであるEC2利用してチャットサービスを公開してみたいと思います。
記事が長くなってしまう為、今回はEC2に乗せるアプリケーションを用意していきましょう。
アプリケーションの作成
最終的なディレクトリ構造は下記のようになります。かなりシンプルです。
'chatExample' ├── app.js ├── index.html ├── node_modules └── package.json
パッケージマネージャーである、npmを使用して作業していきます。
npmの使い方が分からない方はこちらを参考に導入してみましょう。
知っておいて損はなし!新人Webデザイナーのための「npm」入門|ferret [フェレット]
では実際に作業していきましょう。ディレクトリの作成とpakage.jsonを作成します。
$ mkdir chatExample $ cd chatExample $ npm init
$ npm init
で依存関係をまとめたJSONファイルが作成されるのですが、途中で色々と聞かれるのですが今回はエンター連打で問題ないです。
次に今回使うモジュールのインストールと、サーバー側で動かすapp.jsと、クライアント側に表示するindex.htmlを用意しましょう。使用するモジュールは下記の二つです。
socket.io Socket.IO
$ npm -i npm socket.io express --save $ touch app.js index.html
これでモジュールのインストールと、必要なファイルの作成が出来たので。作成したapp.jsとindex.htmlを下記の通り編集します。
'app.js' const app = require('express')(); const http = require('http').Server(app); const io = require('socket.io')(http); app.get('/', (req, res) => { res.sendFile(__dirname + '/index.html'); }); io.on('connection', (socket) => { console.log('a user connected'); socket.on('disconnect', () => { console.log('user disconnected'); }); socket.on('chat message', (msg) => { console.log('message: ' + msg); io.emit('chat message', msg); }); }); http.listen(3000, () => { console.log('listening on *:3000'); });
'index.html' <!doctype html> <html> <head> <title>Socket.IO chat</title> <style> * { margin: 0; padding: 0; box-sizing: border-box; } body { font: 13px Helvetica, Arial; } form { background: #000; 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; } #messages { list-style-type: none; margin: 0; padding: 0; } #messages li { padding: 5px 10px; } #messages li:nth-child(odd) { background: #eee; } </style> </head> <body> <ul id="messages"></ul> <form action=""> <input id="m" autocomplete="off" /><button>Send</button> </form> <script src="/socket.io/socket.io.js"></script> <script src="https://code.jquery.com/jquery-1.11.1.js"></script> <script> $(function () { var socket = io(); $('form').on('submit',() => { socket.emit('chat message', $('#m').val()); $('#m').val(''); return false; }); socket.on('chat message', (msg) => { $('#messages').append($('<li>').text(msg)); }); }); </script> </body> </html>
上記の通り編集が終わりましたら、実行してアプリケーションの動作を確認して見ましょう。
$ node app.js
ブラウザでlocalhost:3000
にアクセスするとアプリケーションが立ち上がってるのが確認出来るかと思います。
ブラウザを二つ開いて確認するとコメントが同期してるのが分かるはずです。
次回はEC2に接続し、このアプリケーションを公開するまでの方法を紹介いたしますのでしばしお待ちください。ではまた!