-
-
Save NetOpWibby/241eb8a96827584f4ec38a8bc4701c14 to your computer and use it in GitHub Desktop.
Node js - Chat Server (NSFW)
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
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