Websockets

Websockets allow you to create a full duplex channel between your clients or between the mobile code and the result page code.

joinMomentChannel(): Websocket Connection and Messaging

joinMomentChannel() creates a websocket connection that can be either authenticated or not. The connection can be seen as a channel that is unique to the Moment and accessible by all the users of that Moment to send/receive messages and sync on topics.

Thanks to the websocket, the developer could, for example, implement Moments based on distributed logics and chats.

Params:

  • onMessage: the message handler function;

  • onError: the error handler function;

  • additional: WsEventHandlers: (optional) additional event handlers:

    • onOpen?: the on connection open callback;

    • onAuth?: the authentication callback;

    • onClose?: the on close connection callback;

  • authenticate: authenticates the user to the websocket (default true).

const onMessage = (data) => console.log(data);
const onError = (err) => console.error(err.message || err);

const onOpen = (data) => console.log('The connection was opened');
const onAuth = (data) => console.log('The user has authenticated');
const onClose = (data) => console.log('Connection closed');

const add = {
  onOpen: onOpen.bind(this),
  onAuth: onAuth.bind(this),
  onClose: onClose.bind(this)
}
const authenticate = true;

SDK.ws.joinMomentChannel(
  onMessage.bind(this), 
  onError.bind(this),
  add, 
  authenticate
);

IMPORTANT NOTES

  • The websocket connection is unique. In the future we might enable more websocket connections at the same time.

  • If one Moment (ie. a user) creates multiple authenticated connection in parallel from the same instance, only the last one will be authenticated. The user can only be authenticated in one single session.

  • If the user needs to receive direct messages, it must be authenticated (set the authenticate flag to true)

sendMessageTo(recipient: string, message: any)

Params:

  • recipient: a user id (its email)

  • message: any javascript object. (it will be serialized to JSON by the MDK).

This function allows to send a message to an authenticated user over the websocket. Both users must be authenticated. If a uses logs on multiple sessions, only the last one will be valid. This means that if the same user logs into the Mobile page and the Result page at the same time only one will be authenticated.

SDK.ws.sendMessageTo('friend@stagecast.se', {
  message: 'Hello Friend, let\'s meet at the bar!'
});

NOTES:

  1. The user must be authenticated to the websocket (ie. have set the authentication param as true in wsConnect())

  2. For now, the function is synchronous, meaning that the MDK doesn't take a callback as an argument. The MDK is being actively developed and future implementations will include this functionality.

broadcastMessage(message: any): boolean

This function allows to broadcast a message to all the users connected to the Moment. If you wish to send a private message to a specific user, or to the Result page see sendMessageTo().

SDK.ws.broadcastMessage({
  message: [
    'Hello Everybody! ',
    'Let\'s meet at the bar. ',
    'I\'ll offer the first round!'
  ].join();
});

Params:

  • message: any javascript object. (it will be serialized to JSON by the MDK).

NOTE

For now, the function is synchronous, meaning that the MDK doesn't take a callback as an argument. The MDK is being actively developed and future implementations will include this functionality.

leaveMomentChannel(): boolean

Used to close the websocket connection.

try {
  const res = SDK.ws.leaveMomentChannel();
} catch (err) {
  console.error(err.message || err);
}

getUserUpdates(): boolean

It is also possible to subscribe to user updates: whenever a user updates its state, the backend broadcast the new state over a special ws channel. You can subscribe to the channel by calling this method.

This usually comes handy when the developer wants to implement dashboard or shared screen that the mobile clients can send messages to. Examples of such screens are the Voting Moment or Collage result pages.

const onMessage = (data) => console.log(data);
const onError = (err) => console.error(err.message || err);

const onOpen = (data) => console.log('The connection was opened');
const onAuth = (data) => console.log('The user has authenticated');
const onClose = (data) => console.log('Connection closed');

const add = {
  onOpen: onOpen.bind(this),
  onAuth: onAuth.bind(this),
  onClose: onClose.bind(this)
}
const authenticate = true;

SDK.ws.getUserUpdates(
  onMessage.bind(this), 
  onError.bind(this),
  add, 
  authenticate
);
  • This channel is readonly: you can only receive messages.

  • If you are planning on creating a Moment for a large crowd use this method carefully. In fact, every client will notified whenever another client updates its state: this usually generate a huge traffic and puts a lot of pressure on the clients.

stopUserUpdates(): boolean

Used to stop getting user updates. This function closes the ws connection opened by getUserUpdates() and handles the teardown logic.

try {
  const res = SDK.ws.stopUserUp();
} catch (err) {
  console.error(err.message || err);
}

Disconnection Listener

Sometimes the moment could lose the connection (when the phone it's locked, the app is put in background etc.). The ws objects allows you register an event listener for the disconnection. You can register your event listener on the window object. The event to listen to is ws-offline

window.addEventListener('ws-offline', 
  (() => console.log('WS disconnected')).bind(this)
);

More on that here: https://developer.mozilla.org/en-US/docs/Web/API/EventTarget/addEventListener

Last updated