Spring Stomp 可以发送未经请求的消息 [英] Spring Stomp CAN send unsolicited messages
问题描述
在 Spring WebSocket 文档中我发现了这句话:
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)
不过我试过这个代码:
@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);
}
}
并且消息按预期每 5000 毫秒广播一次.
And the message is broadcasted every 5000ms as expected.
那么为什么 Spring 文档说服务器不能发送未经请求的消息?
So why Spring docs says that a server cannot send unsollicited messages?
推荐答案
下一句可能意味着在 stomp.js 客户端中您需要设置订阅:
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));
});
春季:
@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.
这篇关于Spring Stomp 可以发送未经请求的消息的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!