#author("2018-08-31T16:17:32+09:00","","")

[[CentOS7]]


*Node.js インストール [#uaec7c16]



サーバーサイド JavaScript 実行環境 Node.js をインストールします。



*Node.js および パッケージ管理ツール npm をインストールします。 [#g5524d06]



|BGCOLOR(black):COLOR(white):|c

|&color(lightpink){# EPELからインストール};|

|[root@localhost ~]# yum --enablerepo=epel -y install nodejs npm|







テストツールを作成して動作確認します。任意の一般ユーザーで実行可能です。



|BGCOLOR(black):COLOR(white):|c

|[root@localhost ~]$ vi helloworld.js|

|var http = require('http'); &br; http.createServer(function (req, res) { &br;   res.writeHead(200, {'Content-Type': 'text/plain'}); &br;   res.end('Hello World\n'); &br; }).listen(1337, '127.0.0.1'); &br; console.log('listening on http://127.0.0.1:1337/'); &br;  &br; &color(lightpink){# 実行}; &br;  &br; |

|[root@localhost ~]$ node helloworld.js &|

|&color(lightpink){# アクセスして確認 (以下のような応答があれば OK)};|

|[root@localhost ~]$ curl http://127.0.0.1:1337/|

|Hello World|







Socket.IO をインストールし、WebSocket を利用した簡易チャットツールを作成して、動作確認します。



|BGCOLOR(black):COLOR(white):|c

|[root@localhost ~]$ npm install socket.io express|

|[root@localhost ~]$ vi chat.js|

|var app = require('express')(); &br; var http = require('http').Server(app); &br; var io = require('socket.io')(http); &br;  &br; app.get('/', function(req, res){ &br;   res.sendFile(__dirname + '/index.html'); &br; }); &br;  &br; io.on('connection', function(socket){ &br;   socket.on('chat message', function(msg){ &br;     io.emit('chat message', msg); &br;   }); &br; }); &br;  &br; http.listen(1337, function(){ &br;   console.log('listening on *:1337'); &br; }); &br; |

|[root@localhost ~]$ vi index.html|

|<!DOCTYPE html> &br; <html> &br; <head> &br; <title>WebSocket Chat</title> &br; </head> &br; <body> &br; <form action=""> &br; <input id="sendmsg" autocomplete="off" /><button>Send</button> &br; </form> &br; <ul id="messages" style="list-style-type: decimal; font-size: 16px; font-family: Arial;"></ul> &br; <script src="/socket.io/socket.io.js"></script> &br; <script src="http://code.jquery.com/jquery.min.js"></script> &br; <script> &br;   var socket = io(); &br;   $('form').submit(function(){ &br;     socket.emit('chat message', $('#sendmsg').val()); &br;     $('#sendmsg').val(''); &br;     return false; &br;   }); &br;   socket.on('chat message', function(msg){ &br;     $('#messages').append($('<li style="margin-bottom: 5px;">').text(msg)); &br;   }); &br; </script> &br; </body> &br; </html>|

|[root@localhost ~]$ node chat.js|

|listening on *:1337|







任意のクライアントコンピュータで Webブラウザを起動し、「http://(サーバーのホスト名またはIPアドレス):1337/」にアクセスして、動作確認します。 複数クライアント、または ブラウザを複数起動すると、動作が確認しやすいでしょう。


トップ   編集 差分 履歴 添付 複製 名前変更 リロード   新規 一覧 検索 最終更新   ヘルプ   最終更新のRSS