繁体   English   中英

无法加载Node.js聊天应用

[英]Node.js chat app doesn't load

我刚刚创建了一个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位,并且正在使用chrome。

提前致谢!

您正在使用net模块创建一个TCP / IP服务器,但是您正在使用Web浏览器使用http协议访问它。

这彼此不匹配。

尝试使用telnet连接到服务器,例如,一切都很好。

或者,如果您希望能够使用Web浏览器进行连接,则需要使用http模块而不是net模块。

网络库,如果用于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/');

打开TCP连接时,请勿使用浏览器进行测试。

只需在控制台中使用telnet localhost 5000进行测试。

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM