Skip to content

Instantly share code, notes, and snippets.

@sapardi
Created February 28, 2012 04:32
Show Gist options
  • Save sapardi/1929501 to your computer and use it in GitHub Desktop.
Save sapardi/1929501 to your computer and use it in GitHub Desktop.
Simple chat program with node.js
var net = require('net');
var carrier = require('carrier');
var connections = [];
net.createServer(function(conn) {
connections.push(conn);
conn.on('close', function() {
var pos = connections.indexOf(conn);
if (pos >= 0) {
connections.splice(pos, 1);
}
});
conn.write("Hello, welcome to this chat server!\n");
conn.write("Please input your name:\n");
var username;
carrier.carry(conn, function(line) {
if (!username) {
username = line;
conn.write("Hello " + username + "!\n");
return;
}
if (line == 'quit') {
conn.end();
return;
}
var feedback = username + ": " + line + "\n";
connections.forEach(function(one_connection) {
one_connection.write(feedback);
});
});
}).listen(4000);
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment