JavaScript Client

powerful. fast. easy.

The AMPS JavaScript Client lets you write cross-platform messaging applications for both web apps working in a browser, as well as server-side applications that use Node.js. It uses the power of WebSocket technology combined with asyncronous nature of JavaScript.

Quick Start

It is very easy to start using the AMPS JavaScript client. You are just a few steps away from having a working application! Download the most recent version of the client, extract amps.js, and put it in your project.

Node.js
1 var amps = require('./amps');

Browser
1 <!-- Optional import, provides support for obsolete browsers like IE6 -->
2 <script src="es6-promise.min.js"></script>
3 <script src="amps.js"></script>

You are now ready to use AMPS in your project!

Here are a few JavaScript examples to get you started:

EXAMPLE 1: CONNECT AND SUBSCRIBE

In this example, we connect to an AMPS server running locally and initiate a subscription to the orders topic.

 1 var client = new amps.Client('my-application');
 2 
 3 client.connect('ws://localhost:9100/amps/json')
 4     .then(function() {
 5         // Connected, let's subscribe to a topic now
 6         return client.subscribe(
 7             function(message) {
 8                 console.log(message.data);
 9             }, 
10             'orders'
11         );
12     })
13     .then(function(subscriptionId) {  // Once we subscribed, the subscriptionId is passed down the chain
14         console.log(subscriptionId);
15         client.publish('orders', {order: 'Tesla 3', qty: 10});
16     })
17 	.catch(function(error) {
18         // This can be either a connection error or a subscription error, thanks to Promises!
19         return console.log(error);
20     });

As new orders are posted, the message handler is invoked with each message, and prints the data of each order to the console. Since every command (except publish()) returns a Promise, it is very easy to chain commands and handle errors:

 1 function onMessage(message) {
 2     console.log('message: ', message);
 3 }
 4 
 5 client.connect('ws://localhost:9100/amps/json')
 6     .then(() => client.subscribe(onMessage, 'orders'))         // connected, subscribe for the first topic
 7     .then(() => client.subscribe(onMessage, 'reservations'))   // second subscription
 8     .then(() => client.subscribe(onMessage, 'notifications'))  // third subscription
 9 	.catch(function(error) {
10         // if any subscription failed, the chain will end up here
11         return console.log(error);
12     });


EXAMPLE 2: PUBLISH A MESSAGE

With AMPS, publishing is simple, as shown in this example. We connect to an AMPS server running locally, and publish a single message to the messages topic. To simply publish a message, there is no need to predeclare the topic or configure complex routing. Any subscription that has asked for XML messages on the messages topic will receive the message.

1 var client = new amps.Client('publish-example');
2 
3 client.connect('ws://localhost:9100/amps/xml')
4     .then(function() {
5         client.publish('messages', '<hi>Hello, world!</hi>');
6     })
7     .catch(function(err) {
8         console.log(error);
9     });

EXAMPLE 3: DISCONNECT HANDLING

In this example, we need our publishes to the orders topic to continue unabated, even if connectivity to our AMPS server is temporarily interrupted. We use a reconnect function to enable recovery from a connection error. When AMPS detects a connection error, the reconnect function is called to re-establish connection, and our publishing loop continues on once a successful connection is made.

 1 // Assign an error handler that will handle general error such as disconnects
 2 var client = new amps.Client('my-app').errorHandler(function(err) {
 3     console.log(err, 'Reconnecting after 5 seconds...');
 4     setTimeout(function() { reconnect(publisher); }, 5000);
 5 });
 6 
 7 function reconnect(uponConnect) {
 8     client.connect('ws://localhost:9100/amps/json').then(uponConnect);
 9 }
10 
11 var publisher = function() {
12     while (true) {
13         client.publish('orders', readAnOrder());
14     }
15 };
16 
17 // Begin by connecting and publshing
18 reconnect(publisher);

EXAMPLE 4: QUERY THE CONTENTS OF A STATE-OF-THE-WORLD TOPIC

State-of-the-World ("SOW") topics in AMPS combine the power of a database table with the performance of a publish-subscribe system. Use the AMPS JavaScript client to query the contents of a SOW topic.

 1 var client = new amps.Client('my-application');
 2 
 3 client.connect('ws://localhost:9100/amps/json')
 4     .then(function() {
 5         return client.sow(
 6             function(message) {
 7                 if (message.c == 'sow') {
 8                     console.log(message.data);
 9                 }
10             },
11             'orders',
12             "/symbol='ROL'",
13             {
14                 batchSize: 100,
15                 timeout: 5000
16             }
17         );
18     })
19 	.catch(function(error) {
20         console.error('Error: ', error);
21 	});

This example queries for all orders for the symbol ROL, and simply prints the messages to the console.

EXAMPLE 5: COMMAND INTERFACE

Even though AMPS clients provide the above named convenience methods for core AMPS functionality, you can use the Command object to customize the messages that AMPS sends. This is useful for more advanced scenarios where you need precise control over the message, or in cases where you need to use an earlier version of the client to communicate with a more recent version of AMPS, or in cases where a named method is not available.

 1 var client = new amps.Client('my-application');
 2 
 3 client.connect('ws://localhost:9100/amps/json')
 4     .then(function() {
 5         var subscribeCommand = new amps.Command('subscribe').topic('messages').filter('/id > 20');
 6 
 7         return client.execute(subscribeCommand, function(message) {
 8             console.log('message: ', message.data);
 9         });
10     })
11     .catch(function(error) {
12         console.error('Error: ', error);
13     });

This example provides the subscription to a messages topic with a filter applied.

AMPS Server Configuration for Websockets

To configure AMPS for Websocket support, you need to specify the following Transport:

1 <Transports>
2     <Transport>
3         <Name>json-websocket</Name>
4         <Type>tcp</Type>
5         <Protocol>websocket</Protocol>
6         <InetAddr>9100</InetAddr>
7         <MessageType>json</MessageType>
8     </Transport>
9 </Transports>

With the above configuration, AMPS will listen for incoming Websocket connections on port 9100 and will support the json message type. To use TLS/SSL, you'd specify a Certificate and PrivateKey (and optionally the Ciphers):

 1 <Transport>
 2     <Name>json-websocket-secure</Name>
 3     <Type>tcp</Type>
 4     <Protocol>websocket</Protocol>
 5     <InetAddr>9443</InetAddr>
 6     <MessageType>json</MessageType>
 7     <Certificate>./cert.pem</Certificate>
 8     <PrivateKey>./key.pem</PrivateKey>
 9     <Ciphers>HIGH:!aNULL:!MD5:@STRENGTH</Ciphers>
10 </Transport>

Authentication

AMPS provides an option for websocket protocol that controls authentication: WWWAuthenticate. This option provides a flexible way of setting up authorization for the JavaScript client.

The option can have the following values:

  • Negotiate (Kerberos)
  • NTLM
  • Basic realm="Secure Area"

When using Negotiate or NTLM, you don't have to do anything from the JavaScript client: authentication is automatically handled by browser/environment. When using Basic Auth (we recommend using wss in this scenario), you'll need to set a URI of the form wss://user:password@ip:port/amps/json.

By default, no authentication is performed until the 'logon' command is performed after connection.

In order to enable authentication for AMPS JavaScript client, you need to secify the following settings:

  1. Add a protocol in the Protocols section of the config:
    1 <Protocol>
    2     <Name>websocket-portal</Name>
    3     <Module>websocket</Module>
    4     <WWWAuthenticate>Basic realm="Secure Area"</WWWAuthenticate> <!-- Basic Auth -->
    5     <WWWAuthenticate>Negotiate</WWWAuthenticate> <!-- Kerberos-->
    6     <WWWAuthenticate>NTLM</WWWAuthenticate> <!-- NTLM -->
    7 </Protocol>
  2. Specify a transport in the Transports section of the config that will be used for the JavaScript client:
    1 <Transport>
    2     <Name>websocket-auth</Name>
    3     <Type>tcp</Type>
    4     <Protocol>websocket-portal</Protocol>
    5     <InetAddr>9002</InetAddr>
    6 </Transport>

EVERYTHING YOU NEED

If you need more help getting started, the 60East Technologies support and services team is ready to provide the support you need to help you CRANK UP THE AMPS.

The current release of the JavaScript client is version 5.2.1.1, which supports AMPS servers version 5.2 and later.

Documentation

HERE'S THE GOOD STUFF.

If you're ready to CRANK IT UP, here's the information you need to get started. Choose the guide you're looking for, or download a ZIP file with all of the docs.

Visit Documentation Download Documentation