node.jsでwebsoketを試した

環境

手順

Node.jsのインストールとテスト
  • 1. http://nodejs.org/ からダウンロードしてきて、cygwinでconfigure & make & make install
  • 2. httpのテスト

サイトにある例

var http = require('http');
http.createServer(function (req, res) {
  res.writeHead(200, {'Content-Type': 'text/plain'});
  res.end('Hello World\n');
}).listen(8124, "127.0.0.1");
console.log('Server running at http://127.0.0.1:8124/');

> node example.js

    • ブラウザで動くことを確認。
  • 3. tcpのテスト
var net = require('net');
net.createServer(function (socket) {
  socket.setEncoding("utf8");
  socket.write("Echo server\r\n");
  socket.on("data", function (data) {
    socket.write(data);
  });
  socket.on("end", function () {
    socket.end();
  });
}).listen(8124, "127.0.0.1");

> node example.js

    • telnetで動くことを確認

% telnet 127.0.0.1 8124

WebSocketのテスト
var sys = require('sys')
var ws = require('./miksago-node-websocket-server/lib/ws');

var server = ws.createServer();

server.addListener("connection", function(conn){
  sys.log("connection");
  conn.send("Connection: "+conn.id);
});
server.addListener("close", function(conn){
  sys.log("close");
});
server.listen(8000);

> node test.js

  • 4. htmlファイル作成
<html>
<head>
<script language="javascript">
function DP(in_s){
	document.getElementById("output").value += in_s + "\n";
}
function loadTest(){
		var ws = new WebSocket("ws://127.0.0.1:8000/test");
		ws.onopen = function() {
			DP('open');
			ws.send("send");
		};
		ws.onmessage = function (evt) { DP(evt.data); };
		ws.onclose = function() { DP('close'); };
}
</script>
</head>
<body onload="loadTest();">

<textarea id="output" style="width:400px; height:200px;"></textarea>

</body>
</html>
  • 5. chromeでhtmlファイルにアクセスして、サーバーの出力を受け取っていることを確認
npmとsocket.ioのインストールとテスト
$ vi /etc/resolv.conf
--------------------------------------
nameserver 192.168.1.1
--------------------------------------
$ vi ~/.npmrc
--------------------------------------
root = ~/.node_libraries
binroot = ~/.nodejs/bin
manroot = ~/.nodejs/share/man
--------------------------------------
$ curl http://npmjs.org/install.sh | sh
$ ~/.nodejs/bin/npm install socket.io
$ ~/.nodejs/bin/npm install websocket-server
$ vi test.js
--------------------------------
var io = require('socket.io');
--------------------------------