java Spring:向 websocket 客户端发送消息

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/33977844/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-11-02 22:21:52  来源:igfitidea点击:

Spring: send message to websocket clients

javaspringspring-bootrabbitmqspring-websocket

提问by Luiz E.

I'm building a webchat with Spring Boot, RabbitMQ and WebSocket as POC, but I'm stucked a the last point: WebSockets
I want my ws clients to connect to a specific endpoint, like /room/{id}and when a new message arrives, I want the server to send the response to clients, but I searched for something similar and didn't found.

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

Currently, when the message arrives, I process it with RabbitMQ, like

目前,当消息到达时,我用 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()));
            }
        });

what I would like is, instead log it , I want to send it to the client, for example: websocketManager.sendMessage(new String(message.getBody()))

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

回答by Luiz E.

Ok, I think I got it, for everyone who needs it, here is the answer:

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

first, you need to add WS dependencies to the pom.xml

首先,您需要在 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>

create a WS endpoint

创建 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");
    }

}

Note: I'm using STOMP, so the clients should connect like this

注意:我正在使用 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>

Then, you can simply wire the ws messenger on your components with

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

@Autowired
private SimpMessagingTemplate webSocket;

and send the message with

并发送消息

webSocket.convertAndSend(channel, new String(message.getBody()));