node.js を軽くいじったメモ
hello world
$ node > console.log("hello world"); hello world undefined
サーバ起動
- createServer にレスポンスを返すfunctionを渡す
- res.writeHead でレスポンスヘッダを渡す
- res.write でレスポンスボディを渡す
- res.end で終了
var http = require('http'); var server = http.createServer( function(req, res){ res.writeHead(200, { 'Content-Type': 'text/plain' }); res.write('Hello World\n'); res.end(); } ); server.listen(3000); > node server.js
http://localhost:3000 にアクセスすると、
hello world が表示される
Socket.IO を使ってみる
Socket.IOって何?
いろんなブラウザのwebsokectの実装の違いを吸収してくれるライブラリ
ローカルディレクトリにインストール
npm install socket.io
サンプルコード書いてみる
クライアント
<html> <head> <meta charset="utf-8"> <!-- クライアント側のsocket.io.js が違う所にあった --> <script src="./node_modules/socket.io/node_modules/socket.io-client/dist/socket.io.js"></script> <script> var socket = io.connect('http://localhost:3000'); // socket.on が送信 この場合、newsイベントを受信している socket.on('news', function (data) { console.log(data); // socket.emitが送信 この場合、my other event に、オブジェクトを送信している socket.emit('my other event', { my: 'data' }); }); </script> </head> </html>
サーバ
var io = require('socket.io').listen(3000); io.sockets.on('connection', function (socket) { socket.emit('news', { hello: 'world' }); socket.on('my other event', function (data) { console.log(data); }); });
起動
$ node socket.js
クライアントを開くと console に object が届いた
Object { hello="world"}
その後サーバ側でデータを受け取っている
debug - websocket writing 5:::{"name":"news","args":[{"hello":"world"}]} { my: 'data' }
これだけじゃつまらないので、1個のブラウザが投げたイベントを他のクライアントが出すのを作る
soket.broadcast.emit を使う
soket.broadcast.emit は、onイベントの中で使うと、
イベントを投げたクライアント以外の全クライアントにemitするメソッド
クライアント
<script> $(function(){ var socket = io.connect('http://localhost:3000'); socket.on('message', function(data){ console.log(data); message(data); }); socket.emit('login', window.navigator.userAgent); function message(msg){ $("#message").html($("#message").html() + '<br>' + msg); } }); </script>
サーバ
var io = require('socket.io').listen(3000); io.sockets.on('connection', function (socket) { socket.on('login', function (data) { console.log(data); // イベントを送ったクライアントに返信 socket.emit("message", "welcome " + data); // イベントを送った以外の全クライアントに送信 socket.broadcast.emit("message", data +" が来ました"); }); });
2個ブラウザを立ち上げると…
まずはそんなところで