HTTP WebSockets

Contents

HTTP WebSockets

HTTP WebSockets enable two-way communication with HTTP clients

Websockets

Websocket support allows a service to act as a websocket channel that you can connect to from a web-browser.

A get method must be implemented to handle initialization of the websocket.

// Create a websocket if websocket request.
exports.get = function (req) {

  if (!req.webSocket) {
    return {
      status: 404
    };
  }

  return {
    webSocket: {
      data: {
        user: "test"
      },
      subProtocols: ["text"]
    }
  };
};

A websocket event handler named webSocketEvent is required. It will be called for every websocket event from a client. See example below.

// Listen to a websocket event
exports.webSocketEvent = function (event) {

  if (event.type == 'open') {
    // Do something on open
  }

  if (event.type == 'message') {
    // Do something on message recieved
  }

  if (event.type == 'close') {
    // Do something on close
  }

};

Below is an example of a simple chat using the Websocket JS api for sending messages back and adding/removing clients in groups. Adding to groups allows for multicast message sending.

// Lib that contains websocket functions.
var webSocketLib = require('/lib/xp/websocket');

// Listen to a websocket event
exports.webSocketEvent = function (event) {

  if (event.type == 'open') {
    // Send message back to client
    webSocketLib.send(event.session.id, 'Welcome to our chat');

    // Add client into a group
    webSocketLib.addToGroup('chat', event.session.id);
  }

  if (event.type == 'message') {
    // Propegate message to group
    webSocketLib.sendToGroup('chat', event.message);
  }

  if (event.type == 'close') {
    // Remove client from a group
    webSocketLib.removeFromGroup('chat', event.session.id);
  }

};

Contents