如何使用 STOMP 从 Spring WebSocket 服务器向 WebSocket 客户端发送消息?

How to send message to WebSocket client from Spring WebSocket server using STOMP?

我有两个 Spring 使用 STOMP 启动 WebSocket 应用程序:

  1. WebSocket 服务器
  2. WebSocket 客户端

我能够从客户端发送 WebSocket 消息并从服务器响应它。但是,现在我想通过服务器端的事件触发向客户端发送 WebSocket 消息。

有人能告诉我一个方法吗?

这是我现在在服务器端的内容:

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:

@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:/";
    }
}

我在 official spring documentation 上找到了答案。

你只需要注入一个SimpMessagingTemplate

我的控制器现在看起来像这样:

@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:/";
    }
}