6

I have the following code (from the spring websocket demo app) :

    stompClient.connect({}, function(frame) {
        setConnected(true);
        console.log('Connected: ' + frame);
        stompClient.subscribe('/user/queue/greeting', function(greeting) {          
            displayQueueMessage(greeting);
        });

    function sendName() {
      var name = document.getElementById('name').value;
      stompClient.send("/app/wsdemo", {}, JSON.stringify({
        'name' : name
       }));
    }

This is a simple subscribe call for a queue on the server, and another method "sendName()" that sends calls the server.

after sendName is called, the server response to the callback function supplied at the connect method:

function(greeting) {            
    displayQueueMessage(greeting);
});

My question is - how "long" should the client wait from the subscribe call until he can start calling sendName ? I mean, the potential issue i can see here is the following:

i) the client subscribes first for the queue,

ii) the client calls sendName

iii) the server recieves the 2nd call before he recieves the subscribe call.

iv) the response from the server will not be recieved by the client.

my questions:

1) is that scenario really is an issue?

2) how can i avoid it?

3) iv'e read somewhere that since websocket works with tcp, the order of messages is maintained, so my last question is - what about the fallback capability of stompJS for clients with no websocket support? will the order be maintained as well?

Urbanleg
  • 6,252
  • 16
  • 76
  • 139

2 Answers2

0

Since you subscribe to the queue during the connect phase, you just have to wait for the connection to be established before sending requests to the server.

Alessandro Polverini
  • 2,301
  • 19
  • 29
0

I think you fix your problem and now know what is promise, callback and that javascript in asynchronous.

When you subscribe:

  stompClient.subscribe('/user/queue/greeting', function(greeting) {          
        displayQueueMessage(greeting);
    });

you pass callback function as second parameter, and when and only when subscribe happens (successful request) you callback will be executed.

You can avoid it if you will call sendName() in callback, or using any other approach to synchronize that two points.

Ruslan
  • 14,229
  • 8
  • 49
  • 67
  • 1
    That callback is executed when a message is received by the client matching the subscription...not when the subscription is created. – Greg May 18 '17 at 13:21