STOMP网络套接字回调无法正常工作

时间:2016-05-04 04:42:48

标签: javascript html sockets websocket stomp

我正在尝试使用STOMP javascript web套接字连接到mqtt brocker。建立连接。但我的代码中的回调函数没有被调用? 但ping消息是发送的。

我使用网址作为主机地址。 这是我的代码。

<!DOCTYPE html>

<html>
<head>


  <script src="http://cdn.jsdelivr.net/sockjs/0.3.4/sockjs.min.js"></script>
  <script src="stomp.js"></script>

  <script>

var ws = new SockJS('http://108.567.234.143:9876/stomp');


var client = Stomp.over(ws);




client.connect('username', 'pw', connect_callback, on_error);


client.heartbeat.outgoing = 20000; // client will send heartbeats every 20000ms
client.heartbeat.incoming = 0;     // client does not want to receive heartbeats
                                   // from the server

var connect_callback = function() {

   alert("Connected to rabbitMQ");
var subscription = client.subscribe("CRICKET", subs_callback);
console.log('subscribe to CRICKET'); 
};

var on_error =  function(error) {
    console.log('error');
};

var    subs_callback = function(message) {
// called when the client receives a STOMP message from the server
if (message.body) {
  alert("got message with body " + message.body)
//console.log('got message with body' + message.body);
} else {
  alert("got empty message");
}
};


console.log('message.body');


</script>


</head>

<body> 


hello world



</body>
</html>  

我无法订阅某个主题。请告诉我有什么问题? Here is the console log

由于

1 个答案:

答案 0 :(得分:2)

回调是在使用后定义的。

.connect()函数可能会默默地忽略未定义的函数,因此您没有看到任何错误。

在定义回调之后移动.connect()应解决问题。

var ws = new SockJS('http://108.567.234.143:9876/stomp');


var client = Stomp.over(ws);


client.heartbeat.outgoing = 20000; // client will send heartbeats every 20000ms
client.heartbeat.incoming = 0;     // client does not want to receive heartbeats
                                   // from the server

var connect_callback = function() {

   alert("Connected to rabbitMQ");
var subscription = client.subscribe("CRICKET", subs_callback);
console.log('subscribe to CRICKET'); 
};

var on_error =  function(error) {
    console.log('error');
};

var    subs_callback = function(message) {
// called when the client receives a STOMP message from the server
if (message.body) {
  alert("got message with body " + message.body)
//console.log('got message with body' + message.body);
} else {
  alert("got empty message");
}
};


client.connect('username', 'pw', connect_callback, on_error);


console.log('message.body');