java - 如何检测 Spring websocket stomp 订阅消息(帧)?
问题描述
我正在使用 Spring 5:如何检测SUBSCRIBE
来自 Stomp 客户端的消息?
根据我的理解,@SubscribeMapping
只要客户端订阅主题,就应该调用我的控制器方法,但这并没有发生。
这是我的服务器控制器:
@Controller
public class MessageController {
// ...
@MessageMapping("/chat/{mId}")
@SendTo("/topic/messages")
public OutputMessage send(Message message, @DestinationVariable("mId") String mid, MessageHeaders headers, MessageHeaderAccessor accessor) throws Exception {
// ...
}
@SuppressWarnings("unused")
@SubscribeMapping({ "/", "/chat", "/topic/messages", "/messages", "/*" })
public void listen(Message message, MessageHeaders headers, MessageHeaderAccessor accessor) throws Exception {
int i = 0;
System.out.println("subscribed");
}
}
服务器配置:
@Configuration
@ComponentScan(basePackages= { "websockets" })
@EnableWebSocketMessageBroker
public class WebSocketConfig implements WebSocketMessageBrokerConfigurer {
@Override
public void configureMessageBroker(MessageBrokerRegistry config) {
config.enableSimpleBroker("/topic");
config.setApplicationDestinationPrefixes("/app");
}
@Override
public void registerStompEndpoints(StompEndpointRegistry registry) {
registry.addEndpoint("/chat");
registry.addEndpoint("/chat").withSockJS();
}
@Override
public void configureWebSocketTransport(WebSocketTransportRegistration registry) {
WebSocketMessageBrokerConfigurer.super.configureWebSocketTransport(registry);
}
}
和 javascript 客户端:
<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8" />
<title>Chat WebSocket</title>
<script src="sockjs.js"></script>
<script src="stomp.js"></script>
<script type="text/javascript">
// ...
function connect() {
var sock = new SockJS('/<webapp-context>/chat');
stompClient = Stomp.over(sock);
stompClient.connect({}, function(frame) {
setConnected(true);
console.log('Connected: ' + frame);
stompClient.subscribe('/topic/messages', function(messageOutput) {
showMessageOutput(JSON.parse(messageOutput.body));
});
stompClient.subscribe('/topic/messages/13', function(messageOutput) {
showMessageOutput(JSON.parse(messageOutput.body));
});
});
}
// ...
</script>
</head>
<body onload="/*disconnect()*/">
<!-- ... -->
</body>
</html>
该代码已从Intro to WebSockets with Spring改编。
如本答案和文档中所示,我可以只使用拦截器,但是如何@SubscribeMapping
工作呢?
解决方案
您还需要将“主题”注册为应用程序目标主题config.setApplicationDestinationPrefixes({"/app", "/topic"});
。
否则 Spring 不会将订阅消息转发到应用程序,而只会将其转发到消息代理通道。
推荐阅读
- javascript - 如何通过 ajax 将表单发送到我的 php 页面
- javascript - 如何在不需要 ID 的情况下记录嵌套的输入元素值?
- tensorflow - 具有可变依赖关系的`tf.data.Dataset.map`
- python - 如何使用 python 虚拟环境运行 cronjob?
- sql - 如何将不同表中的其他列值获取到查询中?
- java - 如何将 @Nonnull 注释应用于包括类型使用和类型参数在内的所有内容?
- django - 如何将 django web 应用程序部署到谷歌云?
- c# - 如何让 Nuget Gallery 支持 mysql?
- google-apps-script - 隐藏/取消隐藏列
- c# - 桌面方向更改并保持内容不与桌面定向