当前位置: 首页 > article >正文

SpringBoot3.x整合WebSocket

SpringBoot3.x整合WebSocket

本文主要介绍最新springboot3.x下如何整合WebSocket.

WebSocket简述

WebSocket 是一种在单个 TCP 连接上进行全双工通信的协议,它允许在浏览器和服务器之间进行实时的、双向的通信。相对于传统的基于请求和响应的 HTTP 协议,WebSocket 提供了一种更有效、更实时的通信方式,适用于需要实时更新、实时通知和实时交互的应用。

WebSocket 的特点

WebSocket 的一些关键特点包括:

全双工通信: WebSocket 允许服务器和客户端在同一连接上同时进行双向通信。这意味着服务器可以随时向客户端推送数据,而不必等待客户端发送请求。

持久连接: WebSocket 连接一旦建立,会一直保持打开状态,不会像传统的 HTTP 连接那样在每次请求和响应之后关闭。这减少了每次连接建立和关闭的开销,使通信更加高效。

低延迟: 由于连接保持打开状态,WebSocket 通信具有较低的延迟,适用于实时性要求较高的应用,如实时聊天、实时数据更新等。

少量的数据交换: HTTP 请求和响应相比,WebSocket 数据交换的开销较小。WebSocket 的帧头相对较小,因此有效载荷的比例更高。

兼容性: 现代浏览器和大多数服务器支持 WebSocket。此外,WebSocket 协议还定义了一个子协议 STOMPStreaming Text Oriented Messaging Protocol),用于更高级的消息传递和订阅功能。

安全性: 与其他网络通信协议一样,WebSocket 通信也需要一些安全性的考虑。可以使用加密协议(如 TLS)来保护数据在网络传输中的安全性。

实战范例

添加依赖

        <dependency>

            <groupId>org.springframework.boot</groupId>

            <artifactId>spring-boot-starter-websocket</artifactId>

            <version>3.4.2</version>

        </dependency>

配置WebSocket

创建一个配置类来注册WebSocket端点和处理程序。

/**

 * @ 基本功能:

 * @ program:demo-websocket

 * @ author:Jet

 * @ create:2025-02-12 14:14:28

 **/

import cn.jet.demowebsocket.wshandler.EcWebSocketHandler;

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 EcWebSocketHandler(), "/ec").setAllowedOrigins("*");// 注意:在生产环境中,应限制允许的来源

    }

}

实现WebSocket处理器

/**

 * @ 基本功能:

 * @ program:demo-websocket

 * @ author:Jet

 * @ create:2025-02-12 14:16:59

 **/

import cn.jet.demowebsocket.common.EnumHandler;

import cn.jet.demowebsocket.handler.Handler;

import com.fasterxml.jackson.databind.ObjectMapper;

import jakarta.annotation.PostConstruct;

import org.springframework.stereotype.Component;

import org.springframework.web.socket.CloseStatus;

import org.springframework.web.socket.TextMessage;

import org.springframework.web.socket.WebSocketSession;

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

import java.util.HashSet;

import java.util.Map;

import java.util.Set;

@Component

public class EcWebSocketHandler extends TextWebSocketHandler {

    private static Set<WebSocketSession> sessions = new HashSet<>();

    private ObjectMapper objectMapper = new ObjectMapper();

    @Override

    public void afterConnectionEstablished(WebSocketSession session) throws Exception {

        sessions.add(session);

        System.out.println("New session added, session id: " + session.getId());

    }

    @Override

    protected void handleTextMessage(WebSocketSession session, TextMessage message) throws Exception {

        Map<String, Object> param = objectMapper.readValue(message.getPayload(), Map.class);

        System.out.println("from session: " + session.getId());       

        String cmd = param.get("cmd").toString();

        System.out.println("cmd: " + cmd);

        session.sendMessage(new TextMessage("Echo: " + message.getPayload()));

    }

    @Override

    public void afterConnectionClosed(WebSocketSession session, CloseStatus status) throws Exception {

        sessions.remove(session);

        System.out.println("Session closed, session id: " + session.getId());

    }

    @PostConstruct

    public void init() {

        System.out.println("WebSocket handler initialized");

    }

}


http://www.kler.cn/a/550748.html

相关文章:

  • ES常用查询
  • 基于Dify、Ollama与DeepSeek的私有化AI知识库构建:工具作用、场景与优势分析
  • pythonrsa加密与sha256加密
  • 【亚马逊开发者账号02】终审问题SA+review_Pre-review+Doc.xlsx
  • 串的基本操作--数据结构
  • Copilot基于企业PPT模板生成演示文稿
  • AI前端开发赋能自主创业:ScriptEcho助你乘风破浪
  • 【kafka系列】Kafka如何保证消息不丢失?
  • Leetcode 3458. Select K Disjoint Special Substrings
  • qt实现文字跑马灯效果
  • 【CVE-2025-1094】 影响 SQL 注入的 PostgreSQL
  • CMS DTcms 靶场(弱口令、文件上传、tasklist提权、开启远程桌面3389、gotohttp远程登录控制)
  • 基于SSM框架的童装购买平台微信小程序(ssm论文源码调试讲解)
  • 矩阵系统源码搭建之多种剪辑功能技术开发,支持OEM
  • 通俗诠释 DeepSeek-V3 模型的 “671B” ,“37B”与 “128K”,用生活比喻帮你理解模型的秘密!
  • Pikachu靶场-SSRF漏洞
  • matlab模拟风场的随机脉动风
  • Weboffice在线Word权限控制:限制编辑,只读、修订、禁止复制等
  • 点击el-dialog弹框跳到其他页面浏览器的滚动条消失了多了 el-popup-parent--hidden
  • Hadoop 基础原理