How to use AMQP protocol in Browser (JavaScript)

In my previous 2 posts, Connect to Azure Event Hub in browser ( using AMQP over WebSockets ) and Connect to Azure IoT Hub in browser ( using AMQP over WebSockets ), I introduced the parameters needed to connect to IoT Hub and Event Hub. Since we chose to connect in front-end, so we have to find a JavaScript library for AMQP. However, it isn’t quite easy to find one.

rhea is a reactive messaging library based on the AMQP protocol which meet our need.It is a NodeJS project, but it provides a browserify command in script. So all we have to do is to make a little changes.

1.In the type wrapper (types.js), it is designed for Node so it uses Buffer class in code.

if (o instanceof Buffer) {
    return types.wrap_binary(o);

The corresponding data structure in front-end JavaScript is ArrayBuffer. So here we make this code compatible with browser.

if (o instanceof Buffer || o instanceof ArrayBuffer) {
    return types.wrap_binary(o);

2.The library doesn’t implement disconnect method. So let’s add one in container.js

Container.prototype.disconnect = function () {

Now let’s try to browerify the project!
First we need to set dependency.In the terminal, point to project root folder, set the environment variable NODE_PATH to the parent folder of your rhea project. For example, my project folder is C:\Users\v-zhq\IoT\rhea then you will set NODE_PATH to C:\Users\v-zhq\IoT.
Then execute in project folder C:\Users\v-zhq\IoT\rhea:

npm run browserify

rhea.js get!
Then you can use example to test! Point to examples/websockets and start an HTTP server. Then visit http://localhost:8000, input websocket url.

client.html ( in line #31 I made a little change or client object can’t be initialized )

<!DOCTYPE html>
  <title>AMQP websockets example</title>
  <meta http-equiv="content-type" content="text/html;charset=utf-8" />
  <!-- This example was adapted from a chat example included in the
  excellent 'JavaScript: The Definitive Guide', by David Flanagan and
  published by O'Reilly. -->
<script src="rhea.js"></script>

<input type="text" id="request" style="width:100%"/>
var server = prompt("Enter details of server to use", "ws://localhost:5673");
var input = document.getElementById("request");

function append(txt) {
    var node = document.createTextNode(txt);
    var div = document.createElement("div");
    document.body.insertBefore(div, input);
input.onchange = function() {
    input.value = "";

var client = new(require("rhea"))();
client.on("message", function (context) {
var ws = client.websocket_connect(WebSocket);
var connection = client.connect({"connection_details":ws(server, ["AMQPWSB10"]), "reconnect":false});
var sender = connection.open_sender("examples");


Comments (0)

Skip to main content