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

📅 2026-12-01 👤 拼多多助力营销技巧 📂 拼多多助力平台 👁️ 486 次阅读

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

首先,你需要添加Spring WebSocket的依赖到你的pom.xml文件:

...

org.springframework.boot

spring-boot-starter-websocket

...

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

import org.springframework.context.annotation.Configuration;

import org.springframework.web.socket.config.annotation.EnableWebSocketMessageBroker;

import org.springframework.web.socket.config.annotation.WebSocketMessageBrokerConfigurer;

import org.springframework.web.socket.config.annotation.StompEndpointRegistry;

import org.springframework.web.socket.config.annotation.AbstractWebSocketMessageBrokerConfigurer;

import org.springframework.web.socket.config.annotation.PathVariableMapping;

import org.springframework.web.socket.config.annotation.PathVariableMessageHandlerRegistry;

import org.springframework.web.socket.config.annotation.SessionMappingMessageHandlerRegistry;

@Configuration

@EnableWebSocketMessageBroker 拼多多帮助力入口

public class WebSocketConfig extends AbstractWebSocketMessageBrokerConfigurer {

@Override

public void configureMessageBroker(MessageBrokerRegistry config) {

config

.enableSimpleBroker("/topic")

.setApplicationDestinationPrefixes("/app");

}

@Override

public void registerStompEndpoints(StompEndpointRegistry registry) {

registry.addEndpoint("/websocket").withSockJS();

}

}

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

import org.springframework.messaging.simp.SimpMessageTemplate;

import org.springframework.stereotype.Controller;

import org.springframework.web.bind.annotation.RequestMapping;

import org.springframework.web.bind.annotation.RequestMethod;

import org.springframework.web.socket.*;

@Controller

public class WebSocketController {

private SimpMessageTemplate messageTemplate;

public WebSocketController(SimpMessageTemplate messageTemplate) {

this.messageTemplate = messageTemplate;

}

@MessageMapping("/send/{message}")

public void send(@PathVariable String message) {

messageTemplate.convertAndSend("/topic/public", message);

}

}

在上述代码中,我们使用SimpMessageTemplate来发送消息。"/send/{message}"是一个消息映射,它将处理来自客户端的WebSocket消息。消息将被发送到"/topic/public"路径。

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

var socket = new SockJS('/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"路径的消息。当接收到消息时,我们将其打印到控制台。

文章链接

标签: 拼多多助力网站平台 赚钱项目 拼多多助力网 首码项目 手赚APP
拼多多助力营销技巧