Created
January 16, 2012 14:48
-
-
Save emberian/1621196 to your computer and use it in GitHub Desktop.
creationix chat
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 crypto = require('crypto'); | |
var clients = []; | |
var clientNames = {}; | |
Net.createServer(function (client) { | |
clients.push(new Client(client)); | |
}).listen(1337); | |
function Client(socket) { | |
this.socket = socket; | |
this.write("Welcome to the chat server, please ident to gain voice\n"); | |
console.log("A new client connected"); | |
this.socket.setEncoding('utf8'); | |
this.socket.on('data', this.onData.bind(this)); | |
this.socket.on('close', this.onClose.bind(this)); | |
} | |
Client.prototype.commands = ["ident"]; | |
Client.prototype.onData = function (chunk) { | |
if (chunk[0] == "/") { | |
var parts = chunk.substr(1).trim().split(" "); | |
var command = parts.shift(); | |
if (this.commands.indexOf(command) < 0) { | |
this.write("Invalid command\n"); | |
return; | |
} | |
this[command].apply(this, parts); | |
return; | |
} | |
if (!this.username) { | |
this.write("Please ident to gain voice\n"); | |
return; | |
} | |
var message = this.color + this.username + this.normalColor + ": " + chunk; | |
process.stdout.write(message); | |
clients.forEach(function (other) { | |
if (other === this) { return; } | |
other.write(message); | |
}, this); | |
}; | |
Client.prototype.onClose = function () { | |
clients.splice(clients.indexOf(this), 1); | |
if (this.username) delete clientNames[this.username]; | |
console.log("%s disconnected", this.username); | |
}; | |
Client.prototype.ident = function (name) { | |
if (clientNames.hasOwnProperty(name)) { j | |
this.write("Sorry, that name is taken\n"); | |
return; | |
} | |
clientNames[name] = this; | |
if (this.username) { | |
delete clientNames[this.username]; | |
console.log("%s renamed to %s", this.username, name); | |
} else { | |
console.log("%s identified", name); | |
} | |
this.username = name; | |
var color = (crypto.randomBytes(1)[0] % 18) + 30; | |
this.color = String.fromCharCode(033) + '[1;' + color + 'm'; | |
this.normalColor = String.fromCharCode(033) + '[1;m'; | |
this.write("You are now identified as " + name + "\n"); | |
} | |
Client.prototype.write = function (message) { | |
return this.socket.write(message); | |
}; | |
console.log("listening on 1337"); |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment