2013-02-12 52 views
0

我剛剛創建了一個node.js聊天應用..但該應用不加載。 代碼是非常基本的Node.js的聊天應用:Node.js聊天應用不加載

// Load the TCP Library 
var net = require('net'); 

// Keep track of the chat clients 
var clients = []; 

// Start a TCP Server 
net.createServer(function (client) { 

    console.log("Connected!"); 

    clients.push(client); 

    client.on('data', function (data) { 
     clients.forEach(function (client) { 
      client.write(data); 
     }); 
    }); 

}).listen(5000); 

// Put a friendly message on the terminal of the server. 
console.log("Chat server is running\n"); 

後,我編譯它,我寫在Chrome瀏覽器localhost:5000但頁面是保持加載和寫不完。

但是,下面的代碼工作完美:

// Load the TCP Library 
net = require('net'); 

// Start a TCP Server 
net.createServer(function (client) { 
    client.write("Hello World"); 
    client.end(); 
}).listen(5000); 


我在我的電腦上運行Windows 7 64位,和我使用的鉻。

在此先感謝!

+1

是否在控制檯中打印'「聊天服務正在運行」? – 2013-02-12 20:41:26

回答

2

您正在使用net模塊創建TCP/IP服務器,但您正在使用您的Web瀏覽器使用http協議訪問它。

這不相互匹配。

嘗試使用telnet連接到您的服務器,例如,一切都應該沒問題。

或者,如果您希望能夠使用Web瀏覽器進行連接,則需要使用http模塊而不是net模塊。

+1

謝謝你!我現在會測試它:) – Israelg99 2013-02-13 13:05:45

1

網絡庫如果用於TCP,不用於HTTP。如果您使用TCS,您應該可以通過telnet訪問您的聊天,但不能通過瀏覽器訪問。

這是如何寫一個用於HTTP(從http://nodejs.org/)的示例

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

非常感謝這個例子! – Israelg99 2013-02-13 13:06:17

1

打開TCP連接時,不要用瀏覽器中測試。

只需在控制檯上用 telnet localhost 5000進行測試。