51 lines
1.2 KiB
JavaScript
51 lines
1.2 KiB
JavaScript
/**
|
|
*
|
|
* User: Martin Donnelly
|
|
* Date: 2016-09-07
|
|
* Time: 15:33
|
|
*
|
|
*/
|
|
const url = require('url');
|
|
const logger = require('log4js').getLogger();
|
|
|
|
module.exports = function(events, wsServer) {
|
|
'use strict';
|
|
|
|
logger.debug('>> new WS', wsServer);
|
|
wsServer.on('connection', function connection(ws) {
|
|
// console.log('>> WS:', ws);
|
|
// const location = url.parse(ws.upgradeReq.url, true);
|
|
|
|
logger.info('Creating event for this connection');
|
|
|
|
logger.info(`${new Date() } Connection accepted.`);
|
|
|
|
const sendSocketHandler = (obj) => {
|
|
logger.debug('sendSocketHandler', obj);
|
|
try {
|
|
ws.send(JSON.stringify(obj));
|
|
}
|
|
catch (err) {
|
|
logger.error(err);
|
|
logger.warn('Offending object: ', obj);
|
|
}
|
|
};
|
|
|
|
events.on('sendSocket', sendSocketHandler);
|
|
|
|
ws.on('message', function(message) {
|
|
console.log('received:', message);
|
|
|
|
if (message === 'update')
|
|
events.emit('update');
|
|
});
|
|
|
|
ws.on('close', function(reasonCode, description) {
|
|
logger.info(`${new Date() } Peer ${ connection.remoteAddress } disconnected.`);
|
|
events.removeListener('sendSocket', sendSocketHandler);
|
|
});
|
|
});
|
|
|
|
return module;
|
|
};
|