2010-10-30 166 views
14

我已經安裝了nodejs,並運行了幾個簡單的例子,例如在一個端口上打開一個服務器並偵聽該端口。nodejs從哪裏開始?

但是,我仍然無法將nodejs與web開發聯繫起來。所以要學習和實現nodejs我正在考慮使用rails和nodejs來製作tic tac腳趾。這可能嗎?

我在設想一個多人遊戲的井字遊戲,如果人1選擇的東西,人2自動在瀏覽器上看到它。

我應該從哪裏開始?

我在rails中有經驗,但在nodejs或nodejs + rails中沒有。

回答

2

我建議看看項目Socket.IO和Socket.IO節點。它使用HTML5 WebSockets的(如果可用),並且回落自動和優雅(無需干預)到Flash插槽,並根據需要

XHR輪詢這裏有一個腳本下載文件:

mkdir socket.io 
cd socket.io 
git clone https://github.com/LearnBoost/Socket.IO.git --recursive 
git clone https://github.com/LearnBoost/Socket.IO-node.git --recursive 

這裏的服務器。 js文件:

var http=require('http'); 
var url=require('url'); 
var fs=require('fs'); 
var sys=require('sys'); 
var io=require('./socket.io/Socket.IO-node'); //adjust path as necessary... 

var server=http.createServer(function(req,res){ 
    res.writeHead(200,{'Content-Type':'text/html'}); 
    res.write('Hello world'); 
    res.end(); 
}); 
server.listen(8000); 

var socket=io.listen(server); 

socket.on('connection', function(client){ 
    onConnection(client); 
    client.on('message', function(){ 
    onMessage(); 
    }) 
    client.on('disconnect', function(){ 
    onDisconnect(); 
    }) 
}); 
function onConnection(client){ 
    console.log('connection'); 
    //client.connected; //tests if connected 
    //client.send("message"); 
    //client.broadcast("message"); //send to all other conns 
} 
function onMessage(){ 
    console.log('message'); 
} 
function onDisconnect(){ 
    console.log('disconnect'); 
} 

}); 

sudo node server.js

運行上面的服務器,這是你的index.html在兄弟中運行wser:

<script src="./socket.io/Socket.IO/socket.io.js" type="text/javascript" charset="utf-8"></script> <!--Adjust path as necessary--> 
<script> 
var host="localhost"; 
var port=8000; 

var socket=new io.Socket(host,{'port':port}); 

socket.connect(); 
socket.on('connect',function(){onConnect();}) 
socket.on('message',function(data){onMessage(data);}) 
socket.on('disconnect',function(){onDisconnect();}); 

function onConnect(){ 
    ///alert('connect'); 
} 
function onMessage(data){ 
    //alert('message'); 
} 
function onDisconnect(){ 
    //alert('disconnect'); 
    socket.connect(); 
} 

</script>