下面我将为您详细讲解Spring Boot 2.0集成WebSocket实现后台向前端推送信息的完整攻略。
一、WebSocket简介
WebSocket是一种在单个TCP连接上进行全双工通信的协议。它使得客户端和服务器之间数据的交换变得更加实时和高效。在Web场景中,WebSocket被广泛应用于实时通信、聊天室、在线游戏等领域。
二、Spring Boot 2.0集成WebSocket的步骤
在Spring Boot 2.0中,集成WebSocket非常容易。下面我们来逐步实现。
1.创建Spring Boot项目
使用Spring Initializr快速创建一个Spring Boot项目,选择自己熟悉的构建工具和依赖选项即可。
2.添加WebSocket依赖
在maven的pom.xml文件中添加如下依赖:
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-websocket</artifactId>
</dependency>
这个依赖会为我们提供所需的所有WebSocket库和配置。
3.编写WebSocket配置类
在Spring Boot 2.0中,可以使用两种方式来配置WebSocket,分别是注解和Java配置。这里我们使用Java配置来实现WebSocket配置。
新建一个WebSocketConfig类,添加@EnableWebSocket注解启用WebSocket功能,并实现WebSocketConfigurer接口中的registerWebSocketHandlers方法,代码如下:
@Configuration
@EnableWebSocket
public class WebSocketConfig implements WebSocketConfigurer {
@Override
public void registerWebSocketHandlers(WebSocketHandlerRegistry registry) {
registry.addHandler(new WebSocketHandler(), "/ws").setAllowedOrigins("*");
}
}
其中,WebSocketHandler是我们自己实现的一个WebSocket处理器,后面会详细讲解。
4.编写WebSocket处理器
编写WebSocket处理器,实现WebSocketHandler接口,重写onOpen、onClose、onMessage等方法。这个处理器负责处理与客户端之间的WebSocket连接和交互,因此这里的onMessage方法是和客户端进行交互的核心代码。下面是一个简单的WebSocketHandler实现:
public class WebSocketHandler implements WebSocketHandler {
private static final Logger logger = LoggerFactory.getLogger(WebSocketHandler.class);
@Override
public void afterConnectionEstablished(WebSocketSession webSocketSession) throws Exception {
logger.info("WebSocket session opened: " + webSocketSession.getId());
}
@Override
public void handleMessage(WebSocketSession webSocketSession, WebSocketMessage<?> webSocketMessage) throws Exception {
logger.info("Received message: " + webSocketMessage.getPayload());
}
@Override
public void afterConnectionClosed(WebSocketSession webSocketSession, CloseStatus closeStatus) throws Exception {
logger.info("WebSocket session closed: " + webSocketSession.getId());
}
}
5.推送信息到前端
推送信息到前端可以通过WebSocketSession的sendMessage方法实现。我们可以稍加修改之前的WebSocketHandler,实现在onMessage方法中将信息推送给客户端:
public class WebSocketHandler implements WebSocketHandler {
private static final Logger logger = LoggerFactory.getLogger(WebSocketHandler.class);
private List<WebSocketSession> sessions = new ArrayList<>();
@Override
public void afterConnectionEstablished(WebSocketSession webSocketSession) throws Exception {
logger.info("WebSocket session opened: " + webSocketSession.getId());
sessions.add(webSocketSession);
}
@Override
public void handleMessage(WebSocketSession webSocketSession, WebSocketMessage<?> webSocketMessage) throws Exception {
logger.info("Received message: " + webSocketMessage.getPayload());
// 推送消息到前端
for (WebSocketSession session : sessions) {
if (session.isOpen()) {
TextMessage message = new TextMessage("当前时间:" + new Date());
session.sendMessage(message);
}
}
}
@Override
public void afterConnectionClosed(WebSocketSession webSocketSession, CloseStatus closeStatus) throws Exception {
logger.info("WebSocket session closed: " + webSocketSession.getId());
sessions.remove(webSocketSession);
}
}
这里我们在WebSocketHandler中新建了一个sessions数组,用来保存客户端与服务器之间的WebSocketSession会话。在afterConnectionEstablished方法中,将当前会话添加到sessions数组中。在onMessage方法中,遍历sessions数组,向所有客户端推送当前的时间信息。在afterConnectionClosed方法中,从sessions数组中删除会话。
三、示例说明
下面是两个示例说明,分别是前端和后端:
1.前端代码
在HTML页面的JavaScript代码中,使用WebSocket连接服务器,并在onmessage回调中处理接受服务器推送的信息,代码如下:
<!DOCTYPE html>
<html>
<head>
<title>WebSocket Test</title>
<meta charset="utf-8"/>
</head>
<body>
<h1>WebSocket Test</h1>
<div id="msg"></div>
<script type="text/javascript">
const webSocket = new WebSocket("ws://localhost:8080/ws");
webSocket.onmessage = event => {
let msg = document.getElementById("msg");
let time = new Date().toLocaleTimeString();
msg.innerHTML = msg.innerHTML + "<br/>" + "(" + time + ") " + event.data;
}
</script>
</body>
</html>
2.后端代码
为了方便起见,这里直接提供了整个Spring Boot 2.0集成WebSocket的完整后端代码:
@SpringBootApplication
public class Application {
public static void main(String[] args) {
SpringApplication.run(Application.class, args);
}
}
@Configuration
@EnableWebSocket
public class WebSocketConfig implements WebSocketConfigurer {
@Override
public void registerWebSocketHandlers(WebSocketHandlerRegistry registry) {
registry.addHandler(new WebSocketHandler(), "/ws").setAllowedOrigins("*");
}
}
public class WebSocketHandler implements WebSocketHandler {
private static final Logger logger = LoggerFactory.getLogger(WebSocketHandler.class);
private List<WebSocketSession> sessions = new ArrayList<>();
@Override
public void afterConnectionEstablished(WebSocketSession webSocketSession) throws Exception {
logger.info("WebSocket session opened: " + webSocketSession.getId());
sessions.add(webSocketSession);
}
@Override
public void handleMessage(WebSocketSession webSocketSession, WebSocketMessage<?> webSocketMessage) throws Exception {
logger.info("Received message: " + webSocketMessage.getPayload());
// 推送消息到前端
for (WebSocketSession session : sessions) {
if (session.isOpen()) {
TextMessage message = new TextMessage("当前时间:" + new Date());
session.sendMessage(message);
}
}
}
@Override
public void afterConnectionClosed(WebSocketSession webSocketSession, CloseStatus closeStatus) throws Exception {
logger.info("WebSocket session closed: " + webSocketSession.getId());
sessions.remove(webSocketSession);
}
}
您可以使用浏览器访问上述HTML页面,打开控制台查看日志,也可以使用命令行工具进行测试。
本站文章如无特殊说明,均为本站原创,如若转载,请注明出处:SpringBoot2.0集成WebSocket实现后台向前端推送信息 - Python技术站