<!DOCTYPE html>
<html>
   <head>

      <!-- include AutobahnJS .. that's all you need -->
      <script src="http://autobahn.s3.amazonaws.com/js/autobahn.min.js"></script>

      <script>
         // WAMP session object
         var sess = null;

         window.onload = function() {

            var wsuri;
            if (window.location.protocol === "file:") {
               wsuri = "ws://localhost:9000";
            } else {
               wsuri = "ws://" + window.location.hostname + ":9000";
            }

            // connect to WAMP server
            ab.connect(wsuri,

               // WAMP session was established
               function (session) {

                  sess = session;

                  console.log("Connected to " + wsuri);
                  test();
               },

               // WAMP session is gone
               function (code, reason) {

                  sess = null;

                  if (code == ab.CONNECTION_UNSUPPORTED) {
                     window.location = "http://autobahn.ws/unsupportedbrowser";
                  } else {
                     alert(reason);
                  }
               }
            );
         };

         function test()
         {
            // establish a prefix, so we can abbreviate procedure URIs ..
            sess.prefix("calc", "http://example.com/simple/calc#");

            // call a function and log result on success
            sess.call("calc:square", 23).then(ab.log);

            // call a function with multiple arguments
            sess.call("calc:add", 23, 7).then(ab.log);

            // call a function with list of numbers as arg
            sess.call("calc:sum", [1, 2, 3, 4, 5]).then(ab.log);

            // call a function and call another function on success
            sess.call("calc:square", 23).then(function(res) {
               sess.call("calc:sqrt", res).then(ab.log);
            });

            // call a function, log on success, handle error
            sess.call("calc:sqrt", -1).then(ab.log, ab.log);

            // we can throw (see server) and receive a custom error
            sess.call("calc:square", 1001).then(ab.log, ab.log);

            // call a function that takes a long time, call another function
            // the result of the latter is received first, in other words,
            // RPC is really asynchronous
            sess.call("calc:asum", [1, 2, 3]).then(ab.log);
            sess.call("calc:sum", [4, 5, 6]).then(ab.log);

            // we can throw (see server) and receive a custom error
            sess.call("calc:pickySum", [0,1,2,3,4,5]).then(ab.log, ab.log);
         }
      </script>
   </head>
   <body>
      <h1>RPCs with AutobahnJS - Example 2</h1>
      <noscript>
         <span style="color: #f00; font-weight: bold;">
            You need to turn on JavaScript.
         </span>
      </noscript>
      <p>
         Open development console (press F12) to watch.
      </p>
   </body>
 </html>