A rational for why you would want to do this is here
.
I couldn’t find an AMQP library written in browser side JavaScript but I did find a STOMP JavaScript library which works nicely with a server-side STOMP plugin so we use STOMP as our message protocol.
STOMP is a simpler more text-oriented messaging protocol which includes HTTP-like headers. RabbitMQ has a plugin for implementing STOMP and that plugin allows access to AMQP based exchanges and queues by mapping STOMP destinations to exchange/queue names.
You will need:
- Native
WebSockets
orSockJS
on the browser side - The
STOMP.js
browser library - A
SockJS
server which is conveniently available in therabbitmq_web_stomp
plugin forrabbitmq
(bundled withrabbitmq
) - A
STOMP
compliant message broker which is available via therabbitmq_stomp
plugin forrabbitmq
(bundled withrabbitmq
)
Install rabbitmq and enable the plugins:
sudo apt-get install rabbitmq sudo rabbitmq-plugins enable rabbitmq_management sudo rabbitmq-plugins enable rabbitmq_web_stomp sudo service rabbitmq-server restart
Configure exchanges/queues:
- Log into
http://localhost:15672/
with userguest
and passwordguest
. - Create a new test exchange (called
test
in my code) and a new test queue (calledtest
in my code). - Create bindings between the new exchange and queue.
- Manually publish a message in the exchange and ensure it arrives in the queue.
Copy the following two files:
<!-- index.html --> <!DOCTYPE html> <html> <head> <title>Rabbits in the front-end</title> <a href="https://cdnjs.cloudflare.com/ajax/libs/jquery/2.1.4/jquery.js">https://cdnjs.cloudflare.com/ajax/libs/jquery/2.1.4/jquery.js</a> <a href="https://cdnjs.cloudflare.com/ajax/libs/stomp.js/2.3.3/stomp.js">https://cdnjs.cloudflare.com/ajax/libs/stomp.js/2.3.3/stomp.js</a> <a href="http://script.js">http://script.js</a> </head> <body> <form> <input type="text" value=""> <button id="send">Send</button> </form> </body> </html>
/** script.js */ var RabbitMQ = { hostname: window.location.hostname, port: 15674, path: "stomp/websocket", username: "guest", password: "guest", exchange: "/exchange/test", queue: "/queue/test", onMessage: function(message) { alert(message.body); }, onSuccess: function(message) { this.subscribe(RabbitMQ.queue, RabbitMQ.onMessage); }, onError: function() { console.log(arguments); } }; var ws = new WebSocket("ws://" + RabbitMQ.hostname + ":"+RabbitMQ.port+"/"+RabbitMQ.path); var qc = Stomp.over(ws); qc.heartbeat.outgoing = 0; qc.heartbeat.incoming = 0; qc.connect( RabbitMQ.username, RabbitMQ.password, RabbitMQ.onSuccess, RabbitMQ.onError, "/" ); $(window).load(function() { $("form button#send").click(function(e) { e.preventDefault(); var parent = $(this).parent(); if ($("input", parent).val()) { qc.send(RabbitMQ.exchange, null, $("input", parent).val()); $("input", parent).val("") } return false; }); });
And finally visit http://localhost/index.html
to check the results.