/** * * 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 cuid = require('cuid'); const PubSubManager = require('./pubsub'); const logger = require('log4js').getLogger('wshandlerv3'); logger.level = 'debug'; const pubSubManager = new PubSubManager(); function noop() {} function heartbeat() { this.isAlive = true; } module.exports = function(events, wsServer) { 'use strict'; logger.debug('>> new WS', wsServer); wsServer.on('connection', (ws, req) => { ws.cuid = cuid(); console.log(`Connection request for ${ws.cuid}`); ws.isAlive = true; ws.on('pong', heartbeat); ws.on('message', (data) => { console.log(`data: ${ data}`, this); 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.', ws.cuid); pubSubManager.unsubscribe(ws.cuid); }); }); const interval = setInterval(function ping() { wsServer.clients.forEach(function each(ws) { if (ws.isAlive === false) return ws.terminate(); ws.isAlive = false; ws.ping(noop); }); }, 30000); const sendTweetHandler = (id, obj) => { pubSubManager.publishTwitter(id, obj); }; events.on('sendTweet', sendTweetHandler); return module; };