インスパイアされて試してみた
node.js+socket.ioを使ったライブコーディングwebアプリを作ってる - すぎゃーんメモに影響されて,ちょうどnode.jsを触っていたので,自分もnode.js+socket.ioを試してみました.
コードや設定は別途調べて自分なりに書いてみたり.なかなか勉強になりまして,ちょっと分かってきました.試してみたらワクワクしてきますね! リアルタイムな実装が,こんな簡単にできるなんてすごい,
今回は,それらのごくごく基本的な実装と設定周りをまとめました.サンプルコードは,socket.ioを動かすところまでを最小限に記述しています.
node.jsを動作させ始めるまでの道のりはnode.js用の環境作り - ディレクトリ構成とnginxの設定から起動テストまでとか,node.jsとnpmのインストールをしたメモとかを.
サーバーサイドの実装と設定
別途,iptablesとかで,WebSocketが使用する3000番を開いておくこと.socket.ioを試すときは,ポートの開き忘れとcookieに注意も参照のこと.
server.js
3000番で動作.
var http = require('http'), fs = require('fs'), sys = require('sys'), io = require('socket.io'), port = 3000; var server = http.createServer(function(req, res) { // まあ適当 res.writeHead(200, {'Content-Type': 'text/html'}); var rs = fs.createReadStream(__dirname + '/www/index.html'); sys.pump(rs, res); }); var socket = io.listen(server); socket.on('connection', function(client) { // まあ適当2 console.log('client connected'); }); server.listen(port); console.log('Server running at http://127.0.0.1:' + port + '/');
node server.js
server.jsを開始させる.
% node server.js 23 Feb 10:11:16 - [INFO] Started 23 Feb 10:11:16 - socket.io ready - accepting connections Server running at http://127.0.0.1:3000/
nginxの設定
80番をlistenして,中の3000番にproxy_pass.
server { listen 80; server_name example.com; root /hogehoge/public/dev/static; location / { if ( -f $request_filename ) { break; } if ( !-f $request_filename ) { add_header Server "Wheat (node.JS)"; proxy_pass http://127.0.0.1:3000; break; } } }
クライアントサイドの実装
今回は,本当に接続する"だけ"なので適当.
index.html
ブラウザに返すHTMLとJS.server.jsのfs.createReadStreamでパスが通るように設置.
<!DOCTYPE html> <html> <head> <title>socket.io Test</title> <script type="text/javascript" src="/socket.io/socket.io.js"></script> <!-- client.js --> <script type="text/javascript"> socket = new io.Socket(null, {port: 3000}); socket.connect(); socket.on('connect', function() { console.log('connect'); }); </script> </head> <body> <p>WebScoketの接続を確立してみるだけ</p> </body> </html>
接続後のログ
socket.ioは,WebScoketに対応していなくても,クロスブラウザ的に動作するため,websocket以外にもxhr-pollingをはじめとしていくつかの接続モードがあります.いま何で接続されているかは,サーバーのログを見てもいいですし,cookieにあるsocketioを確認してもいいでしょう.
23 Feb xx:xx:xx - Initializing client with transport "xhr-polling" 23 Feb xx:xx:xx - Client xxxxxxxxxxxxxxxx connected client connected 23 Feb xx:xx:xx - Initializing client with transport "websocket" 23 Feb xx:xx:xx - Client xxxxxxxxxxxxxxxx connected client connected