Skip to content

Instantly share code, notes, and snippets.

@ePirat
Created August 11, 2011 23:54
Show Gist options
  • Save ePirat/1141107 to your computer and use it in GitHub Desktop.
Save ePirat/1141107 to your computer and use it in GitHub Desktop.
Node js - Chat Server (NSFW)
Array.prototype.has = function(value) {
var i;
for (var i = 0, loopCnt = this.length; i < loopCnt; i++) {
if (this == value) {
return true;
}
}
return false;
};
var net = require('net');
var sockets = [];
var nicks = [];
var joined = undefined;
var server = net.createServer(function(socket) {
sockets.push(socket);
socket.on('data', function(data) {
var j = sockets.indexOf(socket);
if(nicks[j] == undefined){
var temp = data.toString().replace(/[\n\r\t]/, '');
var temp = temp.replace(/^\s*|\s*$/g,'');
if ((temp != '') && (nicks.has(temp) == false)){
nicks[j] = data.toString().replace(/[\n\r\t]/, '');
joined = true;
} else {
socket.end('Nick invalid!');
joined = undefined;
}
} else { joined = undefined; }
for (var i = 0; i < sockets.length; i++) {
if (sockets[i] == socket) continue;
if (joined != undefined){
sockets[i].write(nicks[j] + " joined the server!\r\n");
} else {
if (nicks[j] != undefined){
sockets[i].write(nicks[j] + ": " + data);
}
}
}
});
socket.on('close', function(exp) {
var i = sockets.indexOf(socket);
sockets.splice(i, 1);
nicks.splice(i, 1);
});
socket.on('error', function(exp) {
var i = sockets.indexOf(socket);
sockets.splice(i, 1);
nicks.splice(i, 1);
});
});
server.listen(8001);
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment