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
# new JsonMessagesProtocol (namedAs: string)
Arguments:
namedAs
: stringThe name of a resulting protocol
Methods
# broadcast (command: string, params: *) instance
Send specified command to all user sessions connected using this protocol
Arguments:
command
: stringCommand to send
params
: *Any value
# getUserSessions (userID: number) → Array.<number> instance
Returns the IDs of all the sessions with established WebSocket connections
Arguments:
userID
: numberUser identifier (from uba_user)
# sendCommand (command: string, recipient: number, params: *) → boolean instance
Send specified command to recipient. Return true
if data has been successfully sent (no guaranty it is received by client)