专业编程教程与实战项目分享平台

网站首页 > 技术文章 正文

Spring Boot3 中 WebSocket 实现数据实时通信全解析

ins518 2025-05-16 13:53:57 技术文章 1 ℃ 0 评论

各位互联网大厂的开发同仁们,在如今的互联网应用开发中,实时通信功能越来越重要。比如在线聊天、数据推送、实时通知等场景,都离不开高效的实时通信技术。而 WebSocket 作为一种高效的双向通信协议,在 Spring Boot3 中能够被轻松整合,从而实现强大的数据实时通信功能。今天,咱们就一起来深入探究一下 Spring Boot3 中如何整合 WebSocket。

WebSocket 简介

WebSocket 是一种网络通信协议,它建立在 TCP 协议之上,与 HTTP 协议有良好的兼容性。其数据格式轻量,性能开销小,并且支持发送文本和二进制数据 ,关键是没有同源限制,客户端可与任意服务器通信。与传统 HTTP 请求 - 响应模式不同,它提供全双工通信通道,允许服务器主动向客户端推送数据,实现双向实时通信。

Spring Boot3 整合 WebSocket 步骤

添加依赖

对于 Spring Boot 项目,若使用内嵌应用容器,引入
spring-boot-starter-websocket依赖即可

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

若部署在独立容器中,如 Tomcat 或 Jetty 等,Spring Boot 假设 WebSocket 配置由容器负责。

配置 WebSocket

MVC 应用中的配置:在基于 Spring MVC 的应用里,创建一个 WebSocket 配置类并实现WebSocketConfigurer接口来注册自定义处理器。

import org.springframework.context.annotation.Configuration;
import org.springframework.web.socket.config.annotation.EnableWebSocket;
import org.springframework.web.socket.config.annotation.WebSocketConfigurer;
import org.springframework.web.socket.config.annotation.WebSocketHandlerRegistry;

@Configuration
@EnableWebSocket
public class WebSocketConfig implements WebSocketConfigurer {
    @Override
    public void registerWebSocketHandlers(WebSocketHandlerRegistry registry) {
        registry.addHandler(new CustomWebSocketHandler(), "/ws").setAllowedOrigins("*");
    }
}

上述配置中,定义了 WebSocket 路径/ws用于客户端连接,CustomWebSocketHandler则用于处理 WebSocket 消息。

定义消息处理类:以简单的消息回显功能为例,创建CustomWebSocketHandler类

import org.springframework.web.socket.handler.TextWebSocketHandler;
import org.springframework.web.socket.TextMessage;
import org.springframework.web.socket.WebSocketSession;

public class CustomWebSocketHandler extends TextWebSocketHandler {
    @Override
    public void handleTextMessage(WebSocketSession session, TextMessage message) throws Exception {
        String clientMessage = message.getPayload();
        session.sendMessage(new TextMessage("echo: " + clientMessage));
    }
}

该类继承TextWebSocketHandler,实现了将接收到的客户端消息回显给客户端的功能。

Reactive 应用中的 WebSocket 支持

在基于 Reactive 模式的应用中,Spring Boot 通过 WebFlux 提供 WebSocket 支持。需引入jakarta.websocket-api和
spring-boot-starter-webflux依赖。

<dependency>
    <groupId>org.springframework.boot</groupId>
    <artifactId>spring-boot-starter-webflux</artifactId>
</dependency>
<dependency>
    <groupId>jakarta.websocket</groupId>
    <artifactId>jakarta.websocket-api</artifactId>
</dependency>

其配置与 MVC 略有不同,可通过 router 函数配置 WebSocket 路径并定义处理器

import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.web.reactive.handler.SimpleUrlHandlerMapping;
import org.springframework.web.reactive.socket.WebSocketHandler;
import org.springframework.web.reactive.socket.server.support.WebSocketHandlerAdapter;
import java.util.Map;

@Configuration
public class ReactiveWebSocketConfig {
    @Bean
    public SimpleUrlHandlerMapping webSocketMapping(CustomReactiveWebSocketHandler handler) {
        return new SimpleUrlHandlerMapping(Map.of("/ws", handler), -1);
    }
    @Bean
    public WebSocketHandlerAdapter handlerAdapter() {
        return new WebSocketHandlerAdapter();
    }
}

接着定义WebSocketHandler实现类处理消息

import org.springframework.web.reactive.socket.WebSocketHandler;
// 后续代码省略

测试 WebSocket 功能

启动 Spring Boot 应用:完成上述配置和代码编写后,启动 Spring Boot 应用。前端测试:编写简单的 HTML 页面测试 WebSocket 连接和消息收发。例如。

<!DOCTYPE html>
<html lang="en">
<head>
    <title>WebSocket测试</title>
</head>
<body>
<div>
    <h2>WebSocket测试页面</h2>
    <div>
        <input type="text" id="messageInput" placeholder="输入消息">
        <button onclick="sendMessage()">发送</button>
    </div>
    <div id="messages" style="margin-top: 20px;"></div>
</div>

<script>
    let ws = null;

    function connect() {
        ws = new WebSocket('ws://localhost:8080/ws');

        ws.onopen = function () {
            console.log('WebSocket连接已建立');
            appendMessage('系统消息:连接已建立');
        };

        ws.onmessage = function (event) {
            appendMessage('收到消息:' + event.data);
        };

        ws.onclose = function () {
            console.log('WebSocket连接已关闭');
            appendMessage('系统消息:连接已关闭');
        };

        ws.onerror = function (error) {
            console.error('WebSocket错误:', error);
            appendMessage('系统消息:连接发生错误');
        };
    }

    function sendMessage() {
        const messageInput = document.getElementById('messageInput');
        const message = messageInput.value;

        if (ws && message) {
            ws.send(message);
            appendMessage('发送消息:' + message);
            messageInput.value = '';
        }
    }

    function appendMessage(message) {
        const messagesDiv = document.getElementById('messages');
        const messageElement = document.createElement('div');
        messageElement.textContent = message;
        messagesDiv.appendChild(messageElement);
    }

    // 页面加载完成后连接WebSocket
    window.onload = connect;
</script>
</body>
</html>

打开浏览器访问该 HTML 页面,在输入框输入消息点击发送,即可看到消息发送到服务端并回显回来。

总结

通过以上步骤,咱们就成功在 Spring Boot3 中整合了 WebSocket 实现数据实时通信。各位开发小伙伴们,赶紧在自己的项目中实践起来吧!

本文暂时没有评论,来添加一个吧(●'◡'●)

欢迎 发表评论:

最近发表
标签列表