首先需要启动RabbitMQ服务端相关的stomp插件rabbitmq_web_stomp
命令如下:rabbitmq-plugins enable rabbitmq_management rabbitmq_web_stomp rabbitmq_stomp
是通过端口15674以websocket的方式来进行连接的
实现代码如下:载入stomp.js和sockjs-0.3.js
<!DOCTYPE html> <html> <head> <title>WebSocket</title> <meta http-equiv="Content-Type" content="text/html; charset=UTF-8"> </head> <body> <div id="main"> <div id="message"></div> </div> </body> <script src="jquery-1.10.2.min.js"></script> <!-- stomp协议的客户端脚本 --> <script src="stomp.js"></script> <!-- SockJS的客户端脚本 --> <script src="sockjs-0.3.js"></script> <script type="text/javascript"> var ws = new WebSocket('ws://192.168.10.182:15674/ws'); // 获得Stomp client对象 var client = Stomp.over(ws); // SockJS does not support heart-beat: disable heart-beats //client.heartbeat.outgoing = 0; //client.heartbeat.incoming = 0; // 定义连接成功回调函数 var on_connect = function(x) { //data.body是接收到的数据 client.subscribe("/exchange/test", function(data) { var msg = data.body; $("#message").append("收到数据:" + msg); }); }; // 定义错误时回调函数 var on_error = function(err) { console.log(err); }; // 连接RabbitMQ client.connect('admin', 'admin', on_connect, on_error, 'vhosttest'); console.log(">>>连接上http://192.168.10.182:15674"); </script> </html>
如此就能收到发送到exchange为test的消息了
用到的js文件可在此下载rabbitmq-stomp