23
20

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

More than 5 years have passed since last update.

Socket.ioを使ってみる

Last updated at Posted at 2015-11-22

#非同期双方向通信を勉強したかったのでSocket.ioを触ってみたときのメモ

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

socket.io
http://socket.io/

環境準備

CentOS7.1

cat /etc/redhat-release
Derived from Red Hat Enterprise Linux 7.1 (Source)

gccをインストール

$ sudo yum -y install gcc
$ gcc --version
gcc (GCC) 4.8.3 20140911 (Red Hat 4.8.3-9)
Copyright (C) 2013 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.29.0

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

$ nvm ls-remote
$ nvm install stable
$ node -v
v5.1.0
$ npm -v
3.3.12

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

package.jsonを作成

package.json
{
  "name": "pulse-sensor",
  "version": "0.0.1",
  "description": "my first socket.io app",
  "dependencies": {
    "express": "4.10.2"
  }
}

expressをインストール

$ npm install --save express@4.10.2

index.jsを作成

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が表示されることを確認。

soket.ioをインストール

$ npm install --save socket.io

package.jsonを修正

package.json
{
  "name": "pulse-sensor",
  "version": "0.0.1",
  "description": "my first socket.io app",
  "dependencies": {
    "express": "4.10.2",
    "socket.io": "1.2.0"
  }
}

index.htmlを作成

  1. フォームに入力されたメッセージをサーバに送信
  2. 受け取ったメッセージを描画
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="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を修正

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つのブラウザで入力したメッセージが他のブラウザにもリアルタイムに反映される事を確認。
思ったより簡単に実装できました。

23
20
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
23
20

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?