Namespace: messages

Session. messages

Messages Feature.

Allow sessions to send and receive messages from the server and other sessions.

Example

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

Classes

FilteredResponseHandler
MessageHandler
MessageStream
Registration
RequestHandler
RequestStream
Responder

Members

<static, readonly> Priority

The priority of the message. Higher priorities are delivered faster.
Properties:
Name Type Default Description
NORMAL 0 Indicates that messages should be delivered with normal priority.
HIGH 1 Indicates that messages should be delivered with high priority.
LOW 2 Indicates that messages should be delivered with low priority.

Methods

addHandler(path, handler, keys) → {Result.<undefined>}

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 Session.messages#listen, received messages provide the sender's SessionId.

Parameters:
Name Type Argument Description
path String The message path to handle
handler Session.messages.MessageHandler The message handler
keys Array <optional>
Message keys to register for this session
Returns:
The registration Result.<undefined>
Type
Result.<undefined>
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
});

addRequestHandler(path, handler, sessionProperties, requestType) → {Result.<Registration>}

Register a request handler to handle requests from other client sessions on a path.
Parameters:
Name Type Argument Description
path String The request path to handle
handler Session.messages.RequestHandler Request handler to be registered at the server
sessionProperties Array <optional>
An optional array containing session properties that should be included with each request
requestType function <optional>
An optional request DataType
Returns:
The registration Result.<Registration>
Type
Result.<Registration>
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
});

listen(path, listener) → {Session.messages.MessageStream}

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 an array of strings and TopicSelectors.

Parameters:
Name Type Argument Description
path String | TopicSelector | Array.<String> The message path
listener function <optional>
The default listener
Returns:
A stream providing messages received on the specific path
Type
Session.messages.MessageStream
Examples
// Create with a default listener function
session.messages.listen('foo', function(message) {
    // Do something with the message
});
// Create a message stream and consume from it
var stream = session.messages.listen('foo');

stream.on('message', function(message) {
     // Do something with the message
});

removeRequestStream(path) → {Session.messages.RequestStream}

Remove the request stream at a particular path.
Parameters:
Name Type Description
path String The path at which to remove the request stream
Returns:
stream - 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), null will be returned instead.
Type
Session.messages.RequestStream

send(path, message, options, target) → {Result.<Session.messages.MessageSendResult>}

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.

Parameters:
Name Type Argument Description
path String The message path
message Object The message value
options Session.messages.SendOptions <optional>
The optional message send options
target String | Object <optional>
The target recipient's session ID (as a string or Session ID object) or a session property filter string.
Returns:
The Result.<Session.messages.MessageSendResult> of the send operation
Type
Result.<Session.messages.MessageSendResult>
Examples
// Send a message to be received by the server and passed to a MessageHandler
session.messages.send('foo', 123);
// Send a message to a specific session
session.messages.send('bar', 'hello', sessionID);
// Send a message with a filter
session.messages.send('baz', 'world', '$Principal is "john"');

sendRequest(path, request, target, requestType, responseType) → {Result}

Send a request. A response is returned when the {Result} is complete.
Parameters:
Name Type Argument Description
path String The path to send the request to
request Object The request to send
target String | Object <optional>
The target recipient's session ID (as a string or Session ID object)
requestType function <optional>
An optional request DataType
responseType function <optional>
An optional response DataType
Returns:
A {Result} containing the response
Type
Result
Examples
// 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');
// 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());
// 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']
  });

sendRequestToFilter(filter, path, request, callback, requestType, responseType) → {Result}

Send a request to all sessions that satisfy a given session filter.
Parameters:
Name Type Argument Description
filter String The session filter expression
path String Message path used by the recipient to select an appropriate handler
request Object The request to send
callback Session.messages.FilteredResponseHandler The handler to receive notification of responses (or errors) from sessions
requestType function <optional>
An optional request DataType
responseType function <optional>
An optional response DataType
Returns:
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.
Type
Result
Examples
// 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() {}});
// 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());

setRequestStream(path, stream, requestType, responseType) → {Session.messages.RequestStream}

Set a request stream to handle requests to a specified path.
Parameters:
Name Type Argument Description
path String The path to receive request on
stream Session.messages.RequestStream The request stream to handle requests to this path
requestType function <optional>
An optional request DataType
responseType function <optional>
An optional response DataType
Returns:
Null if the request stream is the first stream to be set to the path, otherwise this method will return the previously set request stream.
Type
Session.messages.RequestStream
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());

Type Definitions

Message

Type:
  • Object
Properties:
Name Type Description
path String The path that this message was sent on
content Buffer The message's value as a binary buffer
Example
// Read message content as a JSON DataType value
var jsonObj = diffusion.datatypes.json().readValue(message.content).get();

MessageSendResult

Type:
  • Object
Properties:
Name Type Argument Description
path String topic path
recipient String session filter or SessionID of the recipient
sent Number <optional>
the number of sessions the message has been sent to using a filter string
errors Array.<ErrorReport> <optional>
errors from sending to sessions using a filter string

RequestContext

Type:
  • Object
Properties:
Name Type Description
sessionId SessionId SessionId of the session that sent the request
path String the message path of the request
properties Object the session properties

SendOptions

Type:
  • Object
Properties:
Name Type Argument Default Description
priority Session.messages.Priority <optional>
Session.messages.Priority.NORMAL The message priority
headers Array.<String> <optional>
[] The message headers as an array of strings

SessionMessage

Type:
  • Object
Properties:
Name Type Description
path String The path that this message was sent on
content Buffer The message's value as a binary buffer
session String The session that sent this message