I have created a node.js chat site, with the following code :
var net = require("net");
var chatServer = net.createServer(),
clients = [];
chatServer.on('connection', function(client) {
client.write('Welcome');
console.log("Connection is received!");
clients.push(client);
client.on('data', function (data) {
for(var i = 0; i < clients.length; i++) {
clients[i].write(data + "\n");
}
});
client.on('end', function() {
client.end();
});
});
chatServer.listen(8888);
But when I try to connect to localhost:8888, it just keep load till the server is closed.
I figure it out that the following code work perfectly :
var net = require("net");
var chatServer = net.createServer();
chatServer.on('connection', function(client) {
client.write('Hi!');
client.end();
});
chatServer.listen(8888);
So what I did wrong in the chat code?
EDIT: OK, So I actually figured out that when I connect to the server it actually log "Connection is received" which means I can connect to the server, but what I see is the browser trying to load the page. and I cant see the actual server.
You are missing this line which will make server un-responsive.
client.end();