JsonMessagesProtocol

@unitybase/ub/web-sockets~ JsonMessagesProtocol

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

Constructor

new JsonMessagesProtocol(namedAs)

Arguments:
  1. namedAs (String)  The name of a resulting protocol

Extends

Methods

sendCommand(command, recipient, params)Boolean

Send specified command to recipient. Return true if data has been successfully sent (no guaranty it is received by client)
Arguments:
  1. command (String)  Command to send
  2. recipient (Number)  User Session identifier
  3. params (*)  Any value

getUserSessions(userID) → Array.<Number>

Returns the IDs of all the sessions with established WebSocket connections
Arguments:
  1. userID (Number)  User identifier (from uba_user)

broadcast(command, params)

Send specified command to all user sessions connected using this protocol
Arguments:
  1. command (String)  Command to send
  2. params (*)  Any value