telnet を利用して webサーバーと HTTP 通信をしてみる
参考書
- Amazon Web Services 基礎からのネットワーク&サーバー構築 改訂版
- https://www.amazon.co.jp/dp/4822237443/ref=cm_sw_r_tw_dp_U_x_k3p3Cb7VX47T4
流れ
- 1. インスタンス(仮想サーバー)に配置するプログラム(web サーバーを生成・起動するプログラム)を作成する
- 2. インスタンスに node.js をインストールする
- 3. ファイアウォールの設定をする
- 4. 作成したプログラムをインスタンスに配置する
- 5. 生成した web サーバーにリクエストを送信する
1. インスタンスに配置するプログラムを作成する
var http = require("http"); http.createServer(function (req, res) { var data = { RequestHeader: req.headers }; if (req.method == 'GET') { response(res, data); } else if (req.method == 'POST') { req.on('data', function (body) { data.RequestBody = body.toString(); req.on('end', function () { response(res, data); }); }); } }).listen(8080); function response(res, data) { var json = JSON.stringify(data); res.writeHead(200, { 'Content-Type': 'application/json', 'Content-Length': json.length }); res.end(json); }
2. インスタンスに node.js をインストールする
$ ssh -i my-key.pem ec2-user@{インスタンスの固定グローバル IP アドレス}
- 2. 最新の node.js をダウンロードサイト(https://nodejs.org/ja/download/)からインストールします。
$ wget https://nodejs.org/dist/v10.15.3/node-v10.15.3-linux-x64.tar.xz
- 3. インストールしたファイルを展開します。
$ tar Jxvf node-v10.15.3-linux-x64.tar.xz
- 4. パスを通します。(/bin ディレクトリ直下に実行ファイルが存在します。)
export PATH=$PATH:~/node-v10.15.3-linux-x64/bin
3. ファイアウォールの設定をする
作成したプログラムは 8080 番ポートで待ち受けるようにしています。したがって、8080 番ポートを開けます。
- 1. AWS コンソールマネジメントコンソールから「EC2」をクリックします。
- 2. 左側のサイドメニューから「セキュリティグループ」をクリックし、グループ名が「WEB-SG」のセキュリティグループを選択します。
- 3. 画面下部のインバウンドタブ内にある「編集」をクリックします。
- 4. 「ルールの追加」をクリックして行を追加し、タイプを「カスタム TCP ルール」、ポート範囲を「8080」、ソースを「カスタム → 0.0.0.0/0」として「保存」をクリックします。
5. プログラムを実行する
- 1. node コマンドで app.js を実行することで、クライアント上に web サーバー(8080 番ポート)が起動します。
$ node app.js
→ プロンプトからは何も応答がありませんが、これで web サーバー(8080 番ポート)が起動しています。実際にリクエストを投げてみます。
GET リクエストとレスポンス
telnet {インスタンスの固定グローバル IP アドレス} 8080 --------- Trying xxx.xxx.xxx.xxx... Connected to ec2-xxx-xxx-xxx-xxx.ap-northeast-1.compute.amazonaws.com. Escape character is '^]'. // ↓ こちらで入力した部分 GET / HTTP/1.0 User-Agent: OreOreAgent // ↑ こちらで入力した部分 HTTP/1.1 200 OK Content-Type: application/json Content-Length: 46 Date: Sat, 18 May 2019 06:30:58 GMT Connection: close {"RequestHeader":{"user-agent":"OreOreAgent"}}Connection closed by foreign host.
POST リクエストとレスポンス
telnet {インスタンスの固定グローバル IP アドレス} 8080 ---------- Trying xxx.xxx.xxx.xxx... POST / HConnected to ec2-xxx-xxx-xxx-xxx.ap-northeast-1.compute.amazonaws.com. // ↓ こちらで入力した部分 Escape character is '^]'. POST / HTTP/1.0 User-Agent: OreOreAgent Content-Length: 3 abc // ↑ こちらで入力した部分 HTTP/1.1 200 OK Content-Type: application/json Content-Length: 87 Date: Sat, 18 May 2019 06:32:22 GMT Connection: close {"RequestHeader":{"user-agent":"OreOreAgent","content-length":"3"},"RequestBody":"abc"}Connection closed by foreign host.