0


Java 后端websocket 推送前端实现实时刷新

在Java后端使用WebSocket推送信息到前端实现实时刷新的过程涉及到几个关键步骤。下面是一个简单的示例,展示了如何使用Spring Boot和WebSocket来实现这个功能。

首先,你需要添加Spring WebSocket的依赖到你的

pom.xml

文件:

<dependencies>
    ...
    <dependency><groupId>org.springframework.boot</groupId><artifactId>spring-boot-starter-websocket</artifactId></dependency>
    ...
</dependencies>

然后,你需要创建一个WebSocket的配置类,该类将负责处理WebSocket的服务器端点:

importorg.springframework.context.annotation.Configuration;importorg.springframework.web.socket.config.annotation.EnableWebSocketMessageBroker;importorg.springframework.web.socket.config.annotation.WebSocketMessageBrokerConfigurer;importorg.springframework.web.socket.config.annotation.StompEndpointRegistry;importorg.springframework.web.socket.config.annotation.AbstractWebSocketMessageBrokerConfigurer;importorg.springframework.web.socket.config.annotation.PathVariableMapping;importorg.springframework.web.socket.config.annotation.PathVariableMessageHandlerRegistry;importorg.springframework.web.socket.config.annotation.SessionMappingMessageHandlerRegistry;@Configuration@EnableWebSocketMessageBrokerpublicclassWebSocketConfigextendsAbstractWebSocketMessageBrokerConfigurer{@OverridepublicvoidconfigureMessageBroker(MessageBrokerRegistry config){
        config
            .enableSimpleBroker("/topic").setApplicationDestinationPrefixes("/app");}@OverridepublicvoidregisterStompEndpoints(StompEndpointRegistry registry){
        registry.addEndpoint("/websocket").withSockJS();}}

接下来,你需要创建一个控制器,该控制器将处理WebSocket的连接和消息发送:

importorg.springframework.messaging.simp.SimpMessageTemplate;importorg.springframework.stereotype.Controller;importorg.springframework.web.bind.annotation.RequestMapping;importorg.springframework.web.bind.annotation.RequestMethod;importorg.springframework.web.socket.*;@ControllerpublicclassWebSocketController{privateSimpMessageTemplate messageTemplate;publicWebSocketController(SimpMessageTemplate messageTemplate){this.messageTemplate = messageTemplate;}@MessageMapping("/send/{message}")publicvoidsend(@PathVariableString message){
        messageTemplate.convertAndSend("/topic/public", message);}}

在上述代码中,我们使用

SimpMessageTemplate

来发送消息。

"/send/{message}"

是一个消息映射,它将处理来自客户端的WebSocket消息。消息将被发送到

"/topic/public"

路径。

最后,你需要在前端使用JavaScript来连接WebSocket并接收消息。例如,使用SockJS和stompjs库可以很容易地实现这个功能:

var socket =newSockJS('/websocket');// 创建SockJS连接var stompClient = Stomp.over(socket);// 创建stomp客户端
stompClient.connect({},function(frame){// 连接后,发送一个“connect”帧
  console.log('Connected: '+ frame);// 打印连接信息
  stompClient.subscribe('/topic/public',function(message){// 订阅“/topic/public”路径的消息
    console.log('Received: '+ message);// 打印接收到的消息});});

在上述代码中,我们首先创建了一个

SockJS

连接,然后创建了一个

stomp

客户端。当连接成功后,我们订阅了

"/topic/public"

路径的消息。当接收到消息时,我们将其打印到控制台。

标签: java websocket 前端

本文转载自: https://blog.csdn.net/qq_30488445/article/details/132707833
版权归原作者 氵我是大明星 所有, 如有侵权,请联系我们删除。

“Java 后端websocket 推送前端实现实时刷新”的评论:

还没有评论