[英]How to send message to WebSocket client from Spring WebSocket server using STOMP?
I have two Spring Boot WebSocket applications using STOMP:我有两个使用 STOMP 的 Spring Boot WebSocket 应用程序:
I am able to send a WebSocket message from the client and respond to it from the server.我能够从客户端发送 WebSocket 消息并从服务器响应它。 However, now I would like to send a WebSocket message to the client triggered by an event on the server side.
但是,现在我想向由服务器端的事件触发的客户端发送一条 WebSocket 消息。
Can someone tell me a way to do this?有人可以告诉我一种方法吗?
Here is what I have now on the server side:这是我现在在服务器端的内容:
WebSocketConfig.java: WebSocketConfig.java:
@Configuration
@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("/alarm");
}
}
WebSocketController.java: WebSocketController.java:
@Controller
public class WebSocketController {
@MessageMapping("/alarm")
@SendTo("/topic/message")
public void processMessageFromClient(@Payload String message, Principal principal) throws Exception {
System.out.println("WEBSOCKET MESSAGE RECEIVED" + message);
}
@RequestMapping(value = "/start/{alarmName}", method = RequestMethod.POST)
public String start(@PathVariable String alarmName) throws Exception {
System.out.println("Starting " + alarmName);
/* SEND MESSAGE TO WEBSOCKET CLIENT HERE */
return "redirect:/";
}
}
I found the answer on the official spring documentation .我在官方 spring 文档中找到了答案。
You just need to inject a SimpMessagingTemplate
.你只需要注入一个
SimpMessagingTemplate
。
My controller now looks like this:我的控制器现在看起来像这样:
@Controller
public class WebSocketController {
private SimpMessagingTemplate template;
@Autowired
public WebSocketController(SimpMessagingTemplate template) {
this.template = template;
}
@MessageMapping("/alarm")
@SendTo("/topic/message")
public void processMessageFromClient(@Payload String message, Principal principal) throws Exception {
System.out.println("WEBSOCKET MESSAGE RECEIVED" + message);
}
@RequestMapping(value = "/start/{alarmName}", method = RequestMethod.POST)
public String start(@PathVariable String alarmName) throws Exception {
System.out.println("Starting " + alarmName);
this.template.convertAndSend("/topic/message", alarmName);
return "redirect:/";
}
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.