Skip to content

Instantly share code, notes, and snippets.

@erayarslan
Created August 9, 2016 13:30
Show Gist options
  • Select an option

  • Save erayarslan/a72d06f9118e9d6614f7ce518a4f5387 to your computer and use it in GitHub Desktop.

Select an option

Save erayarslan/a72d06f9118e9d6614f7ce518a4f5387 to your computer and use it in GitHub Desktop.
var n3xt = require("n3xt");
var fs = require('fs');
var wstream = fs.createWriteStream('test.txt');
var users = {
data: {},
getUserById: function (id) {
return this.data[id];
},
remoteUserById: function (id) {
delete this.data[id];
},
addUser: function (user) {
this.data[user.id] = user;
}
};
var messageHandler = function (client, data) {
console.log(client.user, data);
client.write("[reply] " + data);
wstream.write(client.id + "_" + data + "\n");
};
var serverTask = function () {
require("net").createServer(1337, function (client) {
client.id = client.remoteAddress + client.remotePort;
client.user = {username: "", password: "", auth: false};
users.addUser(client);
console.log("[USER-CONNECTED]", client.id);
client.on("data", function (data) {
messageHandler(client, data.toString());
});
}).listen(1337, function () {
console.log("[SERVER-TASK]", "Ready");
});
};
n3xt([serverTask]);
process.stdin.resume();
var exitHandler = function (options, err) {
wstream.end();
if (options.cleanup) console.log('clean');
if (err) console.log(err.stack);
if (options.exit) process.exit();
};
//do something when app is closing
process.on('exit', exitHandler.bind(null,{cleanup:true}));
//catches ctrl+c event
process.on('SIGINT', exitHandler.bind(null, {exit:true}));
//catches uncaught exceptions
process.on('uncaughtException', exitHandler.bind(null, {exit:true}));
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment