Options
All
  • Public
  • Public/Protected
  • All
Menu

Interface Messages

Messages Feature.

This feature provides a client session with messaging capabilities. Each message is delivered to a request stream registered with the server. Additionally, the server and other clients can send messages to be received using this feature.

Message requests are sent and received for a particular path. The message path provides a hierarchical context for the recipient.

Message paths are distinct from topic paths. A topic with the path need not exist on the server; if a topic does exist, it is unaffected by messaging. An application can use the same path to associate messages with topics, or an arbitrary path can be chosen.

A message request sent directly to another session is discarded if the receiving session is no longer connected or does not have a stream that matches the message path - an error is returned to the sending session in this case.

Handlers for receiving messages are registered for a path. Each session may register at most one handler for a given path. When dispatching a message, the server will consider all registered handlers and select one registered for the most specific path. If multiple sessions have registered a handler for the same path, one will be chosen arbitrarily.

When registering handlers to receive messages it is also possible to indicate that certain session properties (see Session for a full description of session properties), should be delivered with each message from a client session. The current values of the named properties for the originating session will be delivered with the message.

Messages can also be sent using 'filters', (see Session for a full description of session filters), where the message is delivered to all sessions that satisfy a particular filter expression.

Messages from other clients are received via streams. Streams receive an onClose callback when unregistered and an onError callback if the session is closed.

Request-Response Messaging

Typed request-response messaging allows applications to send requests (of type T) and receive responses (of type R) in the form of a Result. Using Messaging, applications send requests to paths using sendRequest. In order to receive requests, applications must have a local request stream assigned to the specific path, using setRequestStream. When a request is received, the onRequest method on the stream is triggered, to which a response can be sent using the provided respond method call.

One-way Messaging (deprecated)

One-way messaging allows a client to send an untyped message to be sent to a path and be notified that the message has been delivered. No response is possible.

A client can listen for one-way messages for a selection of paths by adding one or more MessageStream implementations. The mapping of selectors to message streams is maintained locally in the client process. Any number of message streams for inbound messages can be added on various selectors.

Access control

A client session needs SEND_TO_MESSAGE_HANDLER permission for the message paths to which it sends messages. If a client sends messages to a message path for which it does not have permission, the message is discarded by the server.

Accessing the feature

Obtain this feature from a session as follows:

Example:

// Get a reference to messaging feature
var messages = session.messages;

Hierarchy

  • Messages

Index

Properties

Priority

Priority: Priority

The Priority enum

Methods

addHandler

  • Register a MessageHandler to receive messages that were sent from other sessions for a particular path but with no specified recipient. The handler must implement the MessageHandler interface.

    The provided handler will be passed messages received on the same path used for registration, or any lower branches. A session may only register a single handler for a given path at a time.

    The message content is dependent on the sender. Correct parsing of the message content from a Buffer is up to the consuming handler.

    Unlike Messages.listen, received messages provide the sender's SessionId.

    Example:

    // Create a message handler
    var handler = {
        onMessage : function(message) {
             console.log(message); // Log the received message
        },
        onActive : function(unregister) {
    
        },
        onClose : function() {
    
        }
    };
    
    // Register the handler
    session.messages.addHandler('foo/bar', handler).then(function() {
        // Registration happened successfully
    }, function(error) {
        // Registration failed
    });
    deprecated

    since 6.2

            One-way messaging is deprecated in favor of request-response
            messaging. See <a href="messages.html#sendrequest">sendRequest</a> and
            <a href="messages.html#sendrequesttofilter">sendRequestToFilter</a>. This method
            will be removed in a future release.

    Parameters

    • path: string

      the message path to handle

    • handler: MessageHandler

      the message handler

    • Optional keys: string[]

      message keys to register for this session

    Returns Result<void>

    the registration Result that completes when the handler has been registered.

addRequestHandler

  • Register a request handler to handle requests from other client sessions on a path.

    Example:

    // Create a request handler that handles strings
    var handler = {
          onRequest: function(request, context, responder) {
              console.log(request); // Log the request
              responder.respond('something');
          },
          onError: function() {},
          onClose: function() {}
      };
    
    // Register the handler
    control.messages.addRequestHandler('test/topic', handler).then(function() {
        // Registration happened successfully
    }, function(error) {
        // Registration failed
    });

    Parameters

    • path: string

      the request path to handle

    • handler: RequestHandler

      request handler to be registered at the server

    • Optional sessionProperties: string[]

      an optional array containing session properties that should be included with each request

    • Optional requestType: DataType<any, any, any>

      an optional request data type

    Returns Result<Registration>

    the registration Result

listen

  • Listen to a stream of messages sent to this Session for a particular path. Messages will be received as message instances.

    The message content is dependent on the sender. Correct parsing of the message content from a Buffer is up to the consuming session.

    Received messages do not indicate which session sent them; if sender information is required then this should be included within the message content.

    The first argument of this function can be a string, a TopicSelector, or a non-empty array of strings and TopicSelectors.

    Example:

    // Create with a default listener function
    session.messages.listen('foo', function(message) {
        // Do something with the message
    });

    Example:

    // Create a message stream and consume from it
    var stream = session.messages.listen('foo');
    
    stream.on('message', function(message) {
         // Do something with the message
    });
    deprecated

    since 6.2

            One-way messaging is deprecated in favor of request-response
            messaging. See <a href="messages.html#sendrequest">sendRequest</a> and
            <a href="messages.html#sendrequesttofilter">sendRequestToFilter</a>. This method
            will be removed in a future release.

    Parameters

    • path: string | TopicSelector | Array<string | TopicSelector>

      the message path or paths to listen to

    • listener: function

      the default listener

    Returns MessageStream

    a stream providing messages received on the specific path

removeRequestStream

  • Remove the request stream at a particular path.

    Parameters

    • path: string

      the path at which to remove the request stream

    Returns RequestStream | undefined

    the request stream that was removed from the path. If the path does not have a request stream assigned (or the path does not exist), undefined will be returned instead.

send

  • Send an arbitrary message to either the server or another session, on a particular path.

    The path does not need to correspond to an existing topic; however the use of / as a hierarchical delimiter allows for other sessions to listen to messages from specific paths.

    The message content may be of any type that can be used for topic updates. It is up to any receiving session to de-serialize it as appropriate.

    An optional argument may be provided to target a specific session or a collection of sessions that satisfy a given filter string. Messages sent will be received if that session has established a MessageStream for the same message path. The ability to send messages to specific sessions or via a filter is determined by permissions assigned to the sender.

    If no session ID or filter is given, the message will be sent to the server and dispatched to a control client that has registered a MessageHandler for the same, or higher, path. There is no guarantee that a MessageHandler will have been established for the path that the message is sent on.

    If no recipient is specified, a successful result will resolve with a single object containing the path that the message was sent to.

    If a session ID was used as the recipient, then the result will resolve with an object containing both path and recipient fields. The result will only resolve when the message has been successfully received by the intended recipient.

    If a session filter was used to send the message, then the result will contain path, recipient, sent and errors fields. The sent field specifies the number of sessions that the filter resolved and successfully sent the message to. The errors field contains an array of errors for any session that could not receive the message.

    Example:

    // Send a message to be received by the server and passed to a MessageHandler
    session.messages.send('foo', 123);

    Example:

    // Send a message to a specific session
    session.messages.send('bar', 'hello', sessionID);

    Example:

    // Send a message with a filter
    session.messages.send('baz', 'world', '$Principal is 'john'');
    deprecated

    since 6.2

            One-way messaging is deprecated in favor of request-response
            messaging. Use <a href="messages.html#sendrequest">            sendRequest</a> instead. This method will be removed in a future
            release.

    Parameters

    • path: string

      the message path

    • message: any

      the message value

    • options: SendOptions

      the optional message send options

    • target: string | SessionId

      the target recipient's session ID (as a string or ession ID object) or a session property filter string.

    Returns Result<MessageSendResult>

    the Result of the send operation

  • Parameters

    • path: string
    • message: any
    • target: string | SessionId

    Returns Result<MessageSendResult>

sendRequest

  • sendRequest(path: string, request: any, target: SessionId | string, requestType?: DataType<any, any, any> | string, responseType?: DataType<any, any, any> | string): Result<any>
  • sendRequest(path: string, request: any, requestType?: DataType<any, any, any> | string, responseType?: DataType<any, any, any> | string): Result<any>
  • Send a request.

    A response is returned when the {Result} is complete.

    Example:

    // Send a string request to be received by the server and passed to a
    // {Session.messages.RequestHandler} registered on the supplied topic
    session.messages.sendRequest('test/topic', 'string request');

    Example:

    // Send a JSON request to be received by the server and passed to a
    // {Session.messages.RequestHandler} registered on the supplied topic
    session.messages.sendRequest('test/topic', diffusion.datatypes.json()
         .from({ 'foo': 'bar'}), diffusion.datatypes.json());

    Example:

    // Send an implicit JSON request to be received by the server and passed to a
    // {Session.messages.RequestHandler} registered on the supplied topic
    session.messages.sendRequest('test/topic', {
        dwarfs: ['sneezy', 'sleepy','dopey',
                 'doc', 'happy', 'bashful',
                 'grumpy']
    });

    Parameters

    • path: string

      the path to send the request to

    • request: any

      the request to send

    • target: SessionId | string

      the target recipient's session ID (as a string or Session ID object)

    • Optional requestType: DataType<any, any, any> | string

      an optional request DataType

    • Optional responseType: DataType<any, any, any> | string

      an optional response DataType

    Returns Result<any>

    a Result containing the response

  • Parameters

    • path: string
    • request: any
    • Optional requestType: DataType<any, any, any> | string
    • Optional responseType: DataType<any, any, any> | string

    Returns Result<any>

sendRequestToFilter

  • Send a request to all sessions that satisfy a given session filter.

    Example:

    // Send a string request to be received by the server and passed to sessions matching the filter.
    session.messages.sendRequestToFilter('$Principal NE 'control'', 'test/topic', 'string request', {
              onResponse : function(sessionID, response) {
                  console.log(response); // Log the response
              },
              onResponseError : function() {},
              onError : function() {},
              onClose : function() {}});

    Example:

    // Send a JSON request to be received by the server and passed to sessions matching the filter.
    session.messages.sendRequestToFilter('$Principal NE 'control'', 'test/topic',
         { dwarfs: ['sneezy', 'sleepy','dopey' ] },
         {
              onResponse : function(sessionID, response) {
                  console.log(response.get()); // Log the response
              },
              onResponseError : function() {},
              onError : function() {},
              onClose : function() {}}, diffusion.datatypes.json(), diffusion.datatypes.json());

    Parameters

    • filter: string

      the session filter expression

    • path: string

      message path used by the recipient to select an appropriate handler

    • request: any

      the request to send

    • callback: FilteredResponseHandler

      the handler to receive notification of responses (or errors) from sessions

    • Optional reqType: DataType<any, any, any>
    • Optional respType: DataType<any, any, any>

    Returns Result<number>

    if the server successfully evaluated the filter, the result contains the number of sessions the request was sent to. Failure to send a request to a particular matching session is reported to the handler.

setRequestStream

  • Set a request stream to handle requests to a specified path.

    Example:

    // Set a request stream handler to handle string requests to 'test/topic'
    var handler = {
          onRequest: function (path, request, responder) {
              console.log(request);
              responder.respond('hello');
          },
          onError: function() {}
      };
    
    control.messages.setRequestStream('test/topic', handler,
                                         diffusion.datatypes.string(), diffusion.datatypes.string());

    Parameters

    • path: string

      the path to receive request on

    • stream: RequestStream

      the request stream to handle requests to this path

    • Optional reqType: DataType<any, any, any>
    • Optional resType: DataType<any, any, any>

    Returns RequestStream | undefined

    undefined if the request stream is the first stream to be set to the path, otherwise this method will return the previously set request stream.