How to properly configure Stomp and SockJS endpoint in Spring MVC?

风流意气都作罢 提交于 2019-12-02 03:56:16

Originaly posted to this question.

This is because stompClient.connect() method is asynchronous. I doesn't pause the execution waiting until connection is established. When you call getNotifications() right after alert() most probably connection is not established yet (it might be established if alert() takes enough time to connect).

You are supposed to call getNotifications() in stompClient.connect() callback (just like you do with stompClient.subscribe()) to be sure that connection is established by the time it gets invoked.

For example:

stompClient.connect({}, function( frame ){
    console.log( "Connected :- "+frame );
    stompClient.subscribe("/topic/notifications", function( notifications ) {
        alert( notifications );
    });
    getNotifications();
}, function( error ) {
    alert( error );
});

Besides of that you may consider using @SubscribeMapping annotation in your java code to get rid of explicit message from JavaScript to get initial message from the server. This way the server sends initial message as soon as subscription is established.

For example:

@MessageMapping(value="/hello")
@SubscribeMapping("/notifications")
@SendTo("/topic/notifications")
public Notify hello() {
    try {
        Thread.sleep(2000);
    } catch (InterruptedException e) {
        // TODO Auto-generated catch block
        e.printStackTrace();
    }
    Notify notify = new Notify();
    notify.setMessage("Hello World !!!");
    return notify;
}

Then client code would look like following:

stompClient.connect({}, function( frame ){
    console.log( "Connected :- "+frame );
    stompClient.subscribe("/topic/notifications", function( notifications ) {
        alert( notifications );
    });
}, function( error ) {
    alert( error );
});
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!