Spring: 向 websocket 客户端发送消息

Spring: send message to websocket clients

我正在使用 Spring Boot、RabbitMQ 和 WebSocket 作为 POC 构建网络聊天,但我被困在最后一点:WebSockets
我希望我的 ws 客户端连接到特定的端点,例如 /room/{id} 并且当新消息到达时,我希望服务器将响应发送给客户端,但我搜索了类似的东西但没有找到。

目前,当消息到达时,我使用 RabbitMQ 对其进行处理,例如

container.setMessageListener(new MessageListenerAdapter(){
            @Override
            public void onMessage(org.springframework.amqp.core.Message message, Channel channel) throws Exception {
                log.info(message);
                log.info("Got: "+ new String(message.getBody()));
            }
        });

我想要的是,而不是记录它,我想将它发送给客户端,例如:websocketManager.sendMessage(new String(message.getBody()))

好的,我想我知道了,给需要的人,这里是答案:

首先需要在pom.xml

中添加WS依赖
<dependency>
    <groupId>org.springframework.boot</groupId>
    <artifactId>spring-boot-starter-websocket</artifactId>
</dependency>
<dependency>
    <groupId>org.springframework</groupId>
    <artifactId>spring-messaging</artifactId>
</dependency>

创建 WS 端点

@Configuration
@EnableWebSocketMessageBroker
public class WebSocketConfig extends AbstractWebSocketMessageBrokerConfigurer {

    @Override
    public void registerStompEndpoints(StompEndpointRegistry registry) {
        // the endpoint for websocket connections
        registry.addEndpoint("/stomp").withSockJS();
    }

    @Override
    public void configureMessageBroker(MessageBrokerRegistry config) {
        config.enableSimpleBroker("/");

        // use the /app prefix for others
        config.setApplicationDestinationPrefixes("/app");
    }

}

注意:我使用的是 STOMP,所以客户端应该这样连接

<script type="text/javascript">
    $(document).ready(function() {
        var messageList = $("#messages");
        // defined a connection to a new socket endpoint
        var socket = new SockJS('/stomp');
        var stompClient = Stomp.over(socket);
        stompClient.connect({ }, function(frame) {
            // subscribe to the /topic/message endpoint
            stompClient.subscribe("/room.2", function(data) {
                var message = data.body;
                messageList.append("<li>" + message + "</li>");
            });

        });
    });
</script>

然后,您可以简单地将 ws messenger 连接到您的组件上

@Autowired
private SimpMessagingTemplate webSocket;

并使用

发送消息
webSocket.convertAndSend(channel, new String(message.getBody()));