Skip to content

Instantly share code, notes, and snippets.

@johncoder
Last active November 8, 2018 14:00
Show Gist options
  • Save johncoder/985b3f3cfd0230d539b4645c400e3532 to your computer and use it in GitHub Desktop.
Save johncoder/985b3f3cfd0230d539b4645c400e3532 to your computer and use it in GitHub Desktop.
A fledgling Socket Server lib
const crypto = require('crypto');
const net = require('net');
function createConnectionId() {
return crypto.randomBytes(16).toString('hex');
};
function create() {
// TODO(john): Timeout & Delete these after idling?
const connectedClients = {};
const handlers = [];
const errHandlers = [];
const server = net.createServer((connection) => {
connection.id = createConnectionId();
connectedClients[connection.id] = connection;
connection.on('close', () => {
delete connectedClients[connection.id];
console.log(`[INFO][TCP] ${connection.id} - connection closed`);
});
connection.on('error', (e) => {
// TODO(john): determine whether an error implies disconnected?
console.log(`[ERROR][TCP] ${connection.id} - ${e}`);
});
connection.on('data', async (data) => {
let error = null;
let handled = true;
const next = (err) => {
handled = false;
error = err;
};
async function execute(handler) {
// TODO(john): Finish implementing separate error handlers
const payload = { connection, data, next };
if (error && handler.length === 2) {
await handler(error, payload);
} else if (!error && handler.length === 1) {
await handler(payload);
} else {
console.log(`[INFO][TCP] ${connection.id} unhandled: ${handler}(${handler.length})`);
}
return handled;
}
for (let i = 0; i < handlers.length; i++) {
const handler = handlers[i];
if (await execute(handler)) {
break;
}
}
});
});
return {
use(handler) {
if (handler.length === 1) {
handlers.push(handler);
} else if (handler.length === 2) {
errHandlers.push(handler);
}
},
handlers,
connectedClients,
server,
};
}
module.exports.create = create;
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment