traintimesPWA/server/lib/wshandlerv3.js

79 lines
1.7 KiB
JavaScript
Raw Normal View History

2020-08-16 19:05:28 +00:00
/**
*
* 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');
2020-08-16 19:05:28 +00:00
const PubSubManager = require('./pubsub');
const logger = require('log4js').getLogger('wshandlerv3');
logger.level = 'debug';
const pubSubManager = new PubSubManager();
function noop() {}
function heartbeat() {
this.isAlive = true;
}
2020-08-16 19:05:28 +00:00
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);
2020-08-16 19:05:28 +00:00
ws.on('message', (data) => {
console.log(`data: ${ data}`, this);
2020-08-16 19:05:28 +00:00
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);
2020-08-16 19:05:28 +00:00
});
});
const interval = setInterval(function ping() {
wsServer.clients.forEach(function each(ws) {
if (ws.isAlive === false) return ws.terminate();
2020-08-16 19:05:28 +00:00
ws.isAlive = false;
ws.ping(noop);
});
}, 30000);
const sendTweetHandler = (id, obj) => {
2020-08-16 19:05:28 +00:00
pubSubManager.publishTwitter(id, obj);
};
events.on('sendTweet', sendTweetHandler);
return module;
};