Spring Stomp CAN send unsolicited messages

天涯浪子 提交于 2020-01-15 06:19:35

问题


In the Spring WebSocket docs I found this sentence:

It is important to know that a server cannot send unsolicited messages.

http://docs.spring.io/spring/docs/current/spring-framework-reference/html/websocket.html (25.4.1)

However I tried this code:

@Controller
public class WebsocketTest {

    @Autowired
    public SimpMessageSendingOperations messagingTemplate;

    @PostConstruct
    public void init(){
        ScheduledExecutorService statusTimerExecutor=Executors.newSingleThreadScheduledExecutor();
        statusTimerExecutor.scheduleAtFixedRate(new Runnable() {                
            @Override
            public void run() {
                messagingTemplate.convertAndSend("/topic/greetings", new Object());
            }
        }, 5000,5000, TimeUnit.MILLISECONDS);
    }
}

And the message is broadcasted every 5000ms as expected.

So why Spring docs says that a server cannot send unsollicited messages?


回答1:


The next sentence might mean that in the stomp.js client you are required to set a subscription:

All messages from a server must be in response to a specific client subscription

But this does not necessarily mean in response to a request. For example a web socket could send information to the following:

Javascript:

stompClient.subscribe('/return/analyze', function(data) {
    generateTableData(JSON.parse(data.body));
 });

Spring:

@Autowired
private SimpMessagingTemplate simpMessagingTemplate;

public void sendSetpoint(String data) throws Exception {
    this.simpMessagingTemplate.convertAndSend("/return/analyze", data);
}

But it cannot send unsolicited messages to the client unless that subscription exists. If this is their intended point it is a little poorly worded.



来源:https://stackoverflow.com/questions/34930703/spring-stomp-can-send-unsolicited-messages

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!