Socket.IOをいじってみたなど
いままでSocket.IOをあまりいじったことがなかったのでいじってみたのです。
割と苦戦したのですが(なんか古い情報だったり、そもそもリファレンスぽいのがなかったり……)なんとかWebSocket的なものは作れたので、一応書き残しておこうかと。
環境:OS X 10.7.5 / node.js 0.8.11
下準備
$ npm i socket.io
Socket.IOをインストールしておきます。
index.js
var fs = require('fs'), http = require('http'), path = require('path'), sio = require('socket.io'), httpServer = http.createServer(), sioServer = sio.listen(httpServer); httpServer.on('request', function (req, res) { var indexPath = path.join(__dirname, 'index.html'); fs.exists(indexPath, function (exists) { if (!exists) { res.writeHead(500); res.end('500'); return; } fs.readFile(indexPath, function (err, data) { if (err) throw err; res.writeHead(200, { 'content-type': 'text/html; charset=utf-8' }); res.end(data); }); }); }); httpServer.listen(3000); var count = 0; sioServer.sockets.on('connection', function (socket) { sioServer.sockets.emit('count change', ++count); socket.on('disconnect', function () { socket.broadcast.emit('count change', --count); }); });
index.html
<!DOCTYPE html> <meta charset="utf-8"> <title>socket.io test</title> <p id="count"></p> <script src="/socket.io/socket.io.js"></script> <script> var socket = io.connect(); socket.on('count change', function (count) { document.getElementById('count').textContent = String(count); }); </script>
実行
$ node index.js
実行したら、ブラウザでhttp://localhost:3000/にアクセスして、タブを増やしたりするとリアルタイムに表示される数が変わるはず。
とまあ、割と巷にあふれてるのだけど一応基本ということで書いてみたのでした。