jmesnil / stomp-websocket

Stomp client for Web browsers and node.js apps
http://jmesnil.net/stomp-websocket/doc/
Apache License 2.0
1.43k stars 586 forks source link

Issue when establishing connection in callback #120

Open timeu opened 9 years ago

timeu commented 9 years ago

I have a weird issue, when I try to esablish a connection in a callback. My use case is that when the user clicks a button, the connection should be established. The backend is RabbitMQ Web-Stomp.

The connection is successfully established when I do it inside the html page (in a script tag).

However when I try to connect in the callback it fails. Here is a version that does not work:

var ws = new WebSocket('ws://127.0.0.1:15674/stomp/websocket');
var client = Stomp.over(ws);

var btn = document.querySelector("#myButton");
btn.app.addEventListener('click', function() {
     client.connect('guest', 'guest', function() {console.log('connected');}, function() {console.log('error');}, '/');
});

In the console I get: Opening Web Socket...

To get the above version to work, I have to move both the ws as well as the client decleration into the callback:

var btn = document.querySelector("#myButton");
btn.app.addEventListener('click', function() {
     var ws = new WebSocket('ws://127.0.0.1:15674/stomp/websocket');
     var client = Stomp.over(ws);
     client.connect('guest', 'guest', function() {console.log('connected');}, function() {console.log('error');}, '/');
});

Console output:

Opening Web Socket...
stomp.min.js:8 Web Socket Opened...
stomp.min.js:8 >>> CONNECT
login:guest
passcode:guest
host:/
accept-version:1.1,1.0
heart-beat:0,0

stomp.min.js:8 <<< CONNECTED
session:session-xunSJWgVMwnj0AAbqXiRIg
heart-beat:0,0
server:RabbitMQ/3.5.4
version:1.1

stomp.min.js:8 connected to server RabbitMQ/3.5.4
stomp.min.js:8 >>> SUBSCRIBE
id:d86d3761-7651-4c79-ad61-2e13e4994ed7
destination:/queue/updates_d86d3761-7651-4c79-ad61-2e13e4994ed7

I also set heartbeat to 0:

client.heartbeat.outgoing = 0;
client.heartbeat.incoming = 0;
rfox90 commented 9 years ago

Can you try without using .over()?

var client = Stomp.client('ws://127.0.0.1:15674/stomp/websocket');

You also might have some scopeing going on?

Have you tried an isolated page?