sachith
sachith

Reputation: 189

STOMP web socket callback doesn't work

I am trying to connect to a mqtt brocker using STOMP javascript web socket. The connection is made. But the callback function in my code is not called? But the ping messages are send.

I am using a url as the host address. Here is my code.

<!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>  

I cant subscribe to a topic. Please tell me what is wrong? Here is the console log

Thanks

Upvotes: 5

Views: 9468

Answers (1)

Akurn
Akurn

Reputation: 392

The callbacks are being defined after they're used.

It's likely the .connect() function is silently ignoring the undefined functions, so you didn't see any errors.

Moving the .connect() to after the callbacks are defined, should fix the issue.

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');

Upvotes: 3

Related Questions