mqtt_server/lib/wshandlerv2.js
2016-11-23 19:19:03 +00:00

53 lines
1.1 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';
wsServer.on('connection', function connection(ws) {
let location = url.parse(ws.upgradeReq.url, true);
logger.info('Creating event for this connection');
logger.info((new Date()) + ' Connection accepted.');
let 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);
});
*/
ws.on('close', function(reasonCode, description) {
logger.info((new Date()) + ' Peer ' + connection.remoteAddress + ' disconnected.');
events.removeListener('sendSocket', sendSocketHandler);
});
});
return module;
};