Socket.IO0.7の勉強

Socket.IOの使い方がわからないのでトップにあるサンプルで流れを確認。

ディレクトリ構成

[16:23]% tree 
.
├── app.js
└── public
    └── index.html

こんな感じのディレクトリ構成にして、

npm install socket.io
npm install express

で、socket.ioとexpressをインストールして、
あとはサンプルをほぼそのまま写す。

サーバ側のapp.js

var express = require('express')
  , app = express.createServer()
  , io = require('socket.io').listen(app);

app.configure(function(){
  app.use(express.static(__dirname + '/public'));
});

app.get('/', function(req, res) {
  res.render('index', {})
});

app.listen(3000);

io.sockets.on('connection', function (socket) {
  console.log('server1: ', Date.now());
  socket.emit('news', { hello: 'world' });
  console.log('server2: ', Date.now());
  socket.on('my other event', function (data) {
    console.log('server3: ', Date.now());
    console.log(data);
  });
});

クライアント側のpublic/index.html

<script src="/socket.io/socket.io.js"></script>
<script>
  console.log('client1: ', Date.now());
  var socket = io.connect('http://localhost');
  socket.on('news', function (data) {
    console.log(data);
    console.log('client2: ', Date.now());
    socket.emit('my other event', { my: 'data' });
    console.log('client3: ', Date.now());
  });
</script>

実行

node app.js

で実行して、chromehttp://localhost:3000へアクセスするとログが吐かれて、



サーバ側は

   debug - websocket writing 1::
server1:  1309591715302
   debug - websocket writing 5:::{"name":"news","args":[{"hello":"world"}]}
server2:  1309591715303
   debug - websocket received data packet 5:::{"name":"my other event","args":[{"my":"data"}]}
server3:  1309591715306
{ my: 'data' }

と出力。


クライアント側のchromeのコンソールには

client1:  1309591715114
Object
hello: "world"
__proto__: Object
client2:  1309591715304
client3:  1309591715304

と出力。

まとめ

ログ確認した感じ、

  • サーバは.on('connection', function(socket){})で、クライアントから接続が来た時の処理を実行できる
    • この引き数のsocketがクライアントとのやり取りで使われる
  • .on('hoge', function(data){})ってやると'hoge'って名前が相手から投げられて来た時の中身をdataという引き数で受け取れる
  • で、その投げる側は.emit('hoge', {})ってやれば'hoge'って名前のオブジェクトを投げられる

って認識すればいいのかな。


で、その他のリファレンスが見たいんだけどどこにあるんだろう?