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 (namedAsstring)

Arguments:
  • namedAs: string

    The name of a resulting protocol

Methods

# broadcast (commandstring, params*) instance

Send specified command to all user sessions connected using this protocol

Arguments:
  • command: string

    Command to send

  • params: *

    Any value

# getUserSessions (userIDnumber) → Array.<number> instance

Returns the IDs of all the sessions with established WebSocket connections

Arguments:
  • userID: number

    User identifier (from uba_user)

# sendCommand (commandstring, recipientnumber, params*) → boolean instance

Send specified command to recipient. Return true if data has been successfully sent (no guaranty it is received by client)

Arguments:
  • command: string

    Command to send

  • recipient: number

    User Session identifier

  • params: *

    Any value