Socket.ioを触ってみる

非同期双方向通信を勉強したかったのでSocket.ioを触った際のメモです。

node.js https://nodejs.org/en/

socket.io http://socket.io/

環境準備

MacOSX Vagrant CentOS7.1

gccをインストール

$ sudo yum -y install gcc
$ gcc --version
gcc (GCC) 4.8.5 20150623 (Red Hat 4.8.5-4)
Copyright (C) 2015 Free Software Foundation, Inc.
This is free software; see the source for copying conditions.  There is NO
warranty; not even for MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.```

node.jsインストール バージョン管理しやすいようにnvm(Node Version Manager)インストール

$ git clone git://github.com/creationix/nvm.git ~/.nvm
$ echo . ~/.nvm/nvm.sh >> ~/.bashrc
$ . ~/.bashrc
$ nvm --version
0.31.0

node.jsの安定版をインストール

$ nvm ls-remote
$ nvm install stable
$ node -v
v5.10.1
$ npm -v
3.8.3

とりあえずGet Started: Chat applicationをやってみる

package.jsonを作成

{
  "name": "socket-chat-example",
  "version": "0.0.1",
  "description": "my first socket.io app",
  "dependencies": {}
}

expressをインストール

$ npm install --save express@4.10.2

index.jsを作成

var app = require('express')();
var http = require('http').Server(app);

app.get('/', function(req, res){
res.send('<h1>Hello world</h1>');
});

http.listen(3000, function(){
console.log('listening on *:3000');
});

実行

$ node index.js

ブラウザから3000ポートでアクセスすると Hello worldが表示されることを確認。

f:id:yamamaijp:20160417180656p:plain

soket.ioをインストール

$ npm install --save socket.io

package.jsonを修正

{
"name": "socket-chat-example",
"version": "0.0.1",
"description": "my first socket.io app",
"dependencies": {
"express": "4.10.2",
"socket.io": "1.2.0"
}
}

index.htmlを作成 1. フォームに入力されたメッセージをサーバに送信 2. 受け取ったメッセージを描画

<!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="https://cdn.socket.io/socket.io-1.2.0.js"></script>
    <script src="http://code.jquery.com/jquery-1.11.1.js"></script>
    <script>
      var socket = io();
      $('form').submit(function(){
        socket.emit('chat message', $('#m').val());
        $('#m').val('');
        return false;
      });
      socket.on('chat message', function(msg){
        $('#messages').append($('<li>').text(msg));
      });
    </script>
  </body>
</html>

index.htmlを返却&受け取ったメッセージを送信するようにindex.jsを修正

var app = require('express')();
var http = require('http').Server(app);
var io = require('socket.io')(http);

app.get('/', function(req, res){
res.sendFile(__dirname + '/index.html');
});

io.on('connection', function(socket){
socket.on('chat message', function(msg){
io.emit('chat message', msg);
console.log('message: ' + msg);
});
});

http.listen(3000, function(){
console.log('listening on *:3000');
});

ctl+Cでindex.jsを停止して再度起動。

$ node index.js

1つのブラウザで入力したメッセージが他のブラウザにもリアルタイムに反映される事を確認。

f:id:yamamaijp:20160417181826p:plain

思ったより簡単に実装できました。