Spring:向WebSocket客户端发送消息

7

我正在使用Spring Boot、RabbitMQ和WebSocket构建一个网络聊天的原型,但是我在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()))

1个回答

10

好的,我想我明白了。对于所有需要它的人,这里是答案:

首先,你需要将WS依赖项添加到pom.xml文件中。

<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()));

4
"channel" 作为你在 convertAndSend 方法中的目标参数来自哪里? - Key Lay
频道是一个字符串。它是我发送消息的“房间”,类似于"/room." .concat(message.getRoom().getUid().toString()) - Luiz E.

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接