使用stomp连接RabbitMQ
1.安装rabbitmq
2.开启stomp插件
- rabbitmq-plugins enable rabbitmq_web_stomp
3.成功后重启RabbitMQ
4.WEB代码
- <!DOCTYPE HTML>
- <html>
- <head>
- <title>MyWebSocket</title>
- </head>
- <body>
- Welcome<br/>
- <input id="text" type="text"/>
- <div id="message">
- </div>
- </body>
- <script src="https://cdn.bootcss.com/stomp.js/2.3.3/stomp.js"></script>
- <script src="https://cdn.bootcss.com/sockjs-client/1.1.4/sockjs.js"></script>
- <script type="text/javascript">
- if(typeofWebSocket=='undefined'){
- console.log('不支持websocket')
- }
- var socketServerUrl = 'http://mq.peos.cn/stomp';
var ws = new SockJS(socketServerUrl);
//var ws = new WebSocket(socketServerUrl);
var client = Stomp.over(ws);//SockJS防断开
client.heartbeat.outgoing = 0; // 客户端不发送
client.heartbeat.incoming = 0; // 客户端每10s接收一次数据从服务器 - var on_connect = function (){
- console.log('connected to '+ socketServerUrl);
- //data.body是接收到的数据
- client.subscribe("/topic/room_1", function (data){
- var msg = data.body;
- $("#msglist").append("<li>收到数据:"+ msg+"</li>");
- });
- };
- var on_error = function (){
- console.log('connected error');
- };
- //参数依次为:用户名,密码,连接后,出错,虚拟主机名
- client.connect('用户名','密码', on_connect, on_error,'/');
- function send(){
- var msg = $('#msg').val();
- //参数依次为:目的地,消息头,消息体
- client.send('/topic/room_1',{},
- JSON.stringify({
- 'room':1,
- 'type':"1",//1,2
- 'content': msg,
- 'userId':"566072523",//小明
- 'questionId':"222299023",//题目1
- 'createTime':"",
- })
- );
- }
- </script>
- <div style="margin-top:100px;">
- <input type="text" id="msg" name="msg" value=""/>
- <input type="button" id="send" name="send" value="send" onclick="send()"/>
- </div>
- <div>
- <ul id="msglist">
- </ul>
- </div>
- </html>