Simple protocol for exchanging JSON commands.
Each message transferred by a web socket is a JSON with two attributes
{command: {String}, params: {*}}
Inside WebSocket threads, the class can be used to subscribe to messages arrived from clients
and assign handlers to it (if you need to receive web socket messages in server):
const WebSockets = require('@unitybase/ub/modules/web-sockets')
var wsNotifier = WebSockets.getWSNotifier()
if (wsNotifier) {
console.debug('Start subscribing to wsNotifier tsts_* events')
wsNotifier.on('tst_echo', function (connection, params) {
connection.send({
command: 'tst_message',
params: {from: connection.session.userID, message: params}
})
})
}
Inside http threads can be used as follows:
const WebSockets = require('@unitybase/ub/modules/web-sockets')
function notifyAboutNewRecord(rowID){
let notifier = WebSockets.getWSNotifier()
if (notifier) {
//send message to ALL connected sessions
notifier.broadcast('ub_entityModification', {action: 'insert', ID: rowID})
//Send to specific user
var userSessions = notifier.getUserSessions(Session.userID)
userSessions.forEach(function(sessionID){
notifier.sendCommand('test_command', sessionID, {action: 'inserted', ID: rowID})
})
}
}
If WebSocket support are enabled in server config then instance of this protocol is accessible via UB.wsNotifier