Skip to content

Instantly share code, notes, and snippets.

@jazzychad
Created December 11, 2009 01:33
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save jazzychad/253906 to your computer and use it in GitHub Desktop.
Save jazzychad/253906 to your computer and use it in GitHub Desktop.
var tcp = require("tcp");
var sys = require("sys");
var chatEmitter = new process.EventEmitter();
Array.prototype.remove = function(e) {
for(var i = 0; i < this.length; i++)
if(e == this[i]) this.splice(i, 1);
}
Array.prototype.each = function(fn) {
for(var i = 0; i < this.length; i++) fn(this[i]);
}
function Client(connection) {
this.name = null;
this.listener = null;
this.connection = connection;
}
var server = tcp.createServer(function (socket) {
var client = new Client(socket);
var chatListener = function(c, msg) {
if (c != client) {
client.connection.send(msg);
}
}
chatEmitter.addListener("chat", chatListener);
client.listener = chatListener;
socket.setTimeout(0);
socket.setEncoding("utf8");
socket.addListener("connect", function () {
socket.send("Welcome, enter your username:\n");
});
socket.addListener("receive", function (data) {
if (client.name == null) {
client.name = data.match(/\S+/);
socket.send("===========\n");
chatEmitter.emit("chat", client, client.name + " has joined.\n");
return;
}
var command = data.match(/^\/(.*)/);
if (command) {
if (command[1] == 'users') {
chatEmitter.emit("chat", client, "- " + c.name + "\n");
}
else if (command[1] == 'quit') {
socket.close();
}
return;
}
chatEmitter.emit("chat", client, client.name + ": " + data);
});
socket.addListener("eof", function() {
socket.close();
});
socket.addListener("close", function() {
chatEmitter.removeListener("chat", client.listener);
chatEmitter.emit("chat", client, client.name + " has left.\n");
client = null;
});
});
server.listen(7000);
sys.puts("listening on port 7000...");
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment