fix(tcp): got server working

This commit is contained in:
Gareth Jones 2018-02-05 08:54:32 +11:00
parent d52734471d
commit ac853f090d
3 changed files with 66 additions and 48 deletions

View File

@ -0,0 +1,39 @@
const debug = require('debug')('log4js:tcp-server');
const net = require('net');
const clustering = require('../clustering');
const LoggingEvent = require('../LoggingEvent');
const send = (data) => {
if (data) {
const event = LoggingEvent.deserialise(data);
clustering.send(event);
}
};
exports.configure = (config) => {
debug('configure called with ', config);
// dummy shutdown if we're not master
let shutdown = (cb) => { cb(); };
clustering.onlyOnMaster(() => {
const server = net.createServer((socket) => {
socket.setEncoding('utf8');
socket.on('data', send);
socket.on('end', send);
});
server.listen(config.port || 5000, config.host || 'localhost', () => {
debug(`listening on ${config.host || 'localhost'}:${config.port || 5000}`);
server.unref();
});
shutdown = (cb) => {
debug('shutdown called.');
server.close(cb);
};
});
return {
shutdown
};
};

View File

@ -1,24 +0,0 @@
const net = require('net');
module.exports = (config, clustering) => {
// dummy shutdown if we're not master
let shutdown = (cb) => { cb(); };
clustering.onlyOnMaster(() => {
const server = net.createServer((socket) => {
socket.setEncoding('utf8');
socket.on('data', clustering.send);
socket.on('end', clustering.send);
});
server.listen(config.port || 5000, config.host || 'localhost', () => {
server.unref();
});
shutdown = (cb) => {
server.close(cb);
};
});
return shutdown;
};

View File

@ -7,38 +7,41 @@ const LoggingEvent = require('../../lib/LoggingEvent');
log4js.configure({
appenders: {
vcr: { type: 'recording' }
vcr: { type: 'recording' },
tcp: { type: 'tcp-server', port: 5678 }
},
categories: {
default: { appenders: ['vcr'], level: 'debug' }
},
listen: {
port: 5678
}
});
test('TCP Server', (batch) => {
batch.test('should listen for TCP messages and re-send via process.send', (t) => {
const socket = net.connect(5678, () => {
socket.write(
(new LoggingEvent('test-category', levels.INFO, ['something'], {})).serialise(),
() => {
socket.end();
log4js.shutdown(() => {
const logs = vcr.replay();
t.equal(logs.length, 1);
t.match(logs[0], {
data: ['something'],
categoryName: 'test-category',
level: { levelStr: 'INFO' },
context: {}
});
t.end();
});
}
);
});
socket.unref();
// give the socket a chance to start up
setTimeout(() => {
const socket = net.connect(5678, () => {
socket.write(
(new LoggingEvent('test-category', levels.INFO, ['something'], {})).serialise(),
() => {
socket.end();
setTimeout(() => {
log4js.shutdown(() => {
const logs = vcr.replay();
t.equal(logs.length, 1);
t.match(logs[0], {
data: ['something'],
categoryName: 'test-category',
level: { levelStr: 'INFO' },
context: {}
});
t.end();
});
}, 100);
}
);
});
socket.unref();
}, 100);
});
batch.end();
});