SpringBoot3集成WebSocket

springboot3,websocket · 浏览次数 : 0

小编点评

**一、简介** WebSocket是一个全双工、双向的通信通道,用于建立和维护客户端和服务器之间的持久连接。WebSocket API允许服务端主动向客户端推送数据,并在浏览器和服务器之间执行双向数据传输。 **二、工程搭建** **1. 项目依赖** 在starter-websocket的依赖中,需要添加以下依赖项: ``` org.springframework.boot spring-boot-starter-websocket ${spring-boot.version} ``` **2. WebSocket 配置** ```java @Configuration @EnableWebSocket public class WebSocketConfig { @Bean public WebSocketEndpoint messageEndpoint() { return new WebSocketEndpoint() { @Override public void handle(Session session, Message message) { // 处理客户端消息 } }; } } ``` **三、WebSocket用法** **1. 连接** 使用 `Session` 对象的 `connect()` 方法来建立连接,并传递用户的 ID。 ```java Session session = ws.connect("/web/socket/msg", "userId"); ``` **2. 发送消息** 使用 `sendMsg()` 方法向指定的会话发送消息。 ```java session.sendText("发送的消息"); ``` **3. 监听消息** 使用 `OnMessage` 事件监听会话中接收的消息,并处理接收的消息。 ```java session.addEventListener(OnMessage.class, message -> { // 处理接收的消息 }); ``` **4. 关闭连接** 使用 `onClose()` 方法关闭连接,并从 `sessions` 中移除该会话。 ```java session.close(); ``` **四、API参考** * `@ServerEndpoint` 注解用于标记该方法为 WebSocket 端点。 * `@OnOpen` 方法用于处理连接建立时执行的操作。 * `@OnMessage` 方法用于处理客户端消息。 * `@OnClose` 方法用于处理连接关闭时执行的操作。 * `@OnError` 方法用于处理发生错误时执行的操作。

正文

标签:WebSocket,Session,Postman。

一、简介

WebSocket通过一个TCP连接在客户端和服务器之间建立一个全双工、双向的通信通道,使得客户端和服务器之间的数据交换变得更加简单,允许服务端主动向客户端推送数据,在WebSocket的API中,浏览器和服务器只需要完成一次握手,两者之间就直接可以创建持久性的连接,并进行双向数据传输。

基于Postman工具的WebSocket交互

Connected to ws://127.0.0.1:8088/web/socket/msg

Handshake Details
Request URL: http://127.0.0.1:8088/web/socket/msg
Request Method: GET
Status Code: 101 

Request Headers
Sec-WebSocket-Version: 13
Sec-WebSocket-Key: 5Qrs8JeRLsiY9G/PRJUocQ==
Connection: Upgrade
Upgrade: websocket
Sec-WebSocket-Extensions: permessage-deflate; client_max_window_bits
Host: 127.0.0.1:8088

Response Headers
Upgrade: websocket
Connection: upgrade
Sec-WebSocket-Accept: E3aFw2bBzxByPCynmQ7lZ+7BgsU=
Sec-WebSocket-Extensions: permessage-deflate;client_max_window_bits=15

二、工程搭建

1、工程结构

2、依赖管理

starter-websocket的依赖中,涉及到spring框架中两个关系较为密切的组件,分别是websocketmessaging组件。

<!--WebSocket-->
<dependency>
    <groupId>org.springframework.boot</groupId>
    <artifactId>spring-boot-starter-websocket</artifactId>
    <version>${spring-boot.version}</version>
</dependency>

三、WebSocket用法

1、示意图

在下面的案例中,大致模拟这样一个流程,三个客户端分别和服务端建立连接,然后进行客户端之间的会话通信。

2、API参考

这里通过4个核心的方法注解,分别处理会话的不同动作,比如连接的建立和关闭,通信交互和错误处理;在实际的应用场景中,需要在通信方法中设计更多的指令来应对不同的业务场景。

@ServerEndpoint("/web/socket/msg")
public class MsgWebSocket {

    private static final  ConcurrentHashMap<String,Session> sessions = new ConcurrentHashMap<>();

    private static final AtomicInteger onlineCount = new AtomicInteger(0);

    /**
     * 建立连接调用的方法
     */
    @OnOpen
    public void onOpen(Session session) {
        String userId = session.getRequestParameterMap().get("userId").get(0);
        // 加入Set中
        sessions.put(userId,session);
        // 在线数增加
        onlineCount.getAndIncrement();
        log.info("session-{},online-count-{}",session.getId(),onlineCount.get());
    }

    /**
     * 客户端消息处理的方法
     */
    @OnMessage
    public void sendMsg(Session sender,String message) throws Exception {
        MsgDTO dto = JSONUtil.toBean(message, MsgDTO.class);
        Session receiver = sessions.get(dto.getUserId());
        if (receiver != null) {
            receiver.getBasicRemote().sendText(dto.getMsg());
        }
    }

    /**
     * 关闭连接调用的方法
     */
    @OnClose
    public void onClose(Session session) {
        String userId = session.getRequestParameterMap().get("userId").get(0);
        // 从Set中删除
        sessions.remove(userId);
        // 在线数减少
        onlineCount.getAndDecrement();
        log.info("session-{},down-line-count-{}",session.getId(),onlineCount.get());
    }

    /**
     * 发生错误调用的方法
     */
    @OnError
    public void onError(Session session, Throwable throwable) throws Exception {
        log.error("Web Stock Error", throwable);
        session.getBasicRemote().sendText(throwable.getMessage());
    }
}

测试效果图:注意这里使用的是postman最新版本。

四、源码参考

文档仓库:
https://gitee.com/cicadasmile/butte-java-note

源码仓库:
https://gitee.com/cicadasmile/butte-spring-parent

与SpringBoot3集成WebSocket相似的内容:

SpringBoot3集成WebSocket

WebSocket通过一个TCP连接在客户端和服务器之间建立一个全双工、双向的通信通道,使得客户端和服务器之间的数据交换变得更加简单。

一文读懂Apollo客户端配置加载流程

SpringBoot集成Apollo源码分析 本文基于 apollo-client 2.1.0 版本源码进行分析 Apollo 是携程开源的配置中心,能够集中化管理应用不同环境、不同集群的配置,配置修改后能够实时推送到应用端,并且具备规范的权限、流程治理等特性。 Apollo支持4个维度管理Key-

Springboot集成Netty实现TCP通讯

Netty

[转帖]Springboot 集成 micrometer(actuator/prometheus) 接口报 404

https://blog.csdn.net/qq_26545503/article/details/123313891 原因 主要是spring-boot版本和micrometer版本没有对应上,我用的spring-boot是2.6.0对应的micrometer就是1.8 需要修改两个地方 pom.

SpringBoot 集成 Quartz + MySQL

Quartz 简单使用 Java SpringBoot 中,动态执行 bean 对象中的方法 源代码地址 => https://gitee.com/VipSoft/VipBoot/tree/develop/vipsoft-quartz 工作原理解读 只要配置好 DataSource Quartz 会

SpringBoot SpringSecurity 介绍(基于内存的验证)

SpringBoot 集成 SpringSecurity + MySQL + JWT 附源码,废话不多直接盘 SpringBoot已经为用户采用默认配置,只需要引入pom依赖就能快速启动Spring Security。 目的:验证请求用户的身份,提供安全访问 优势:基于Spring,配置方便,减少大

Spring Security 报:Encoded password does not look like BCrypt

SpringBoot 集成 Security 时,报 Encoded password does not look like BCrypt 原因:SecurityConfig 必须 Bean 的形式实例化 /** * 配置用户身份的configure()方法 * * @param auth * @t

SpringBoot 集成 SpringSecurity + MySQL + JWT 附源码,废话不多直接盘

SpringBoot 集成 SpringSecurity + MySQL + JWT 无太多理论,直接盘 一般用于Web管理系统 可以先看 SpringBoot SpringSecurity 基于内存的使用介绍 本文介绍如何整合 SpringSecurity + MySQL + JWT 数据结构 数

SpringBoot2.7集成Swagger3

1、引入pom坐标 io.springfox springfox-swagger2 3.0.0

教你如何搞定springboot集成kafka

本文分享自华为云社区《手拉手入门springboot+kafka》,作者:QGS。 安装kafka 启动Kafka本地环境需Java 8+以上 Kafka是一种高吞吐量的分布式发布订阅消息系统,它可以处理消费者在网站中的所有动作流数据。 Kafka启动方式有Zookeeper和Kraft,两种方式只