Last active
October 26, 2016 08:52
-
-
Save DanielKucal/fe74fa1faf8078957fd6 to your computer and use it in GitHub Desktop.
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 server = net.createServer(); | |
var users = []; | |
var tools = require("./tools")(users); | |
server.on('connection', function (conn) { | |
conn.setEncoding("utf8"); | |
conn.write("Hello, what's your name?\r\n"); | |
users.push(conn); | |
conn.data = ''; | |
conn.on('data', function (char) { | |
char = char.toString(); | |
if (char.length > 0 && char.indexOf("\n") > -1 || char.indexOf("\r") > -1) { | |
if (!conn.name) { | |
conn.name = conn.data; | |
tools.say(null, (conn.name + " joined")); | |
} else { | |
tools.say(conn, conn.name + " says: " + conn.data); | |
} | |
conn.data = ''; | |
} else { | |
conn.data += char; | |
} | |
}); | |
conn.on('end', function () { | |
tools.say(null, conn.name + " left"); | |
users.splice(users.indexOf(conn, 1)); | |
}); | |
}).listen(8000); | |
console.log("Server running at port 8000..."); | |
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
module.exports = function(users){ | |
var module = {}; | |
module.say = function (user, msg) { | |
for (var i=0; i < users.length; i++) { | |
if(users[i].writable && users[i] != user) | |
users[i].write(msg + "\r\n"); | |
} | |
}; | |
return module; | |
}; |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment