简体   繁体   中英

Spring websocket and Stomp.js - how long should i wait between subscribe and send?

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?

由于您在连接阶段订阅了队列,因此您只需等待连接建立,然后再向服务器发送请求。

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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM