Created
February 28, 2012 04:32
-
-
Save sapardi/1929501 to your computer and use it in GitHub Desktop.
Simple chat program with node.js
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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