julian
julian

Reputation: 4714

Node.js chat app doesn't load

I just created a node.js chat app.. but the app doesn't load. The code is very basic node.js chat app:

// 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");

After I compile it, I write in the chrome browser localhost:5000 but the page is keep loading and never finish.

However, the following code works perfectly:

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

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


I run Windows 7 64 bit on my computer, and I'm using chrome.

Thanks in Advance!

Upvotes: 0

Views: 226

Answers (3)

nethead
nethead

Reputation: 480

Don't test with browser when opening tcp connection.

Simply test with telnet localhost 5000 in your console.

Upvotes: 1

Hector Correa
Hector Correa

Reputation: 26690

The net library if for TCP, not for HTTP. If you use TCS you should be able to access your chat with telnet but not with the browser.

This is an example on how write one for HTTP (from 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/');

Upvotes: 1

Golo Roden
Golo Roden

Reputation: 150624

You are creating a TCP/IP server by using the net module, but you are accessing it using the http protocol using your web browser.

This does not match each other.

Try to connect to your server using telnet, e.g., and everything should be fine.

Alternatively, if you want to be able to connect using your webbrowser, you need to use the http module instead of the net module.

Upvotes: 2

Related Questions