/** * * User: Martin Donnelly * Date: 2016-09-07 * Time: 15:33 * */ // from // https://medium.com/unprogrammer/implementing-publisher-subscriber-pattern-using-javascript-nodejs-and-websockets-82036da7e174 const url = require('url'); const PubSubManager = require('./pubsub'); const logger = require('log4js').getLogger('wshandlerv3'); logger.level = 'debug'; const pubSubManager = new PubSubManager(); module.exports = function(events, wsServer) { 'use strict'; logger.debug('>> new WS', wsServer); wsServer.on('connection', (ws, req) => { console.log(`Connection request from: ${req.connection.remoteAddress}`); ws.on('message', (data) => { console.log(`data: ${ data}`); const json = JSON.parse(data); const request = json.request; const message = json.message; const channel = json.channel; switch (request) { case 'PUBLISH': pubSubManager.publish(ws, channel, message); break; case 'SUBSCRIBE': pubSubManager.subscribe(ws, channel); break; } }); ws.on('close', () => { console.log('Stopping client connection.'); }); }); const sendTweetHandler = (id, obj) => { logger.debug('sendTweetHandler', id, obj); pubSubManager.publishTwitter(id, obj); /* try { ws.send(JSON.stringify(obj)); } catch (err) { logger.error(err); logger.warn('Offending object: ', obj); } */ }; events.on('sendTweet', sendTweetHandler); return module; };