展开菜单
首页 精品内容 本月促销 装机必备 Windows PDF教程 macOS软件 IOS软件 Android AI 专题
全部分类

当前位置:

首页 > 编程开发 > 怎么使用Spring Boot+Vue实现Socket通知推送

怎么使用Spring Boot+Vue实现Socket通知推送

SpringBoot端第一步,引入依赖首先我们需要引入WebSocket所需的依赖,以及处理输出格式的依赖com.alibabafastjson1.2.73org.springframework.bootspring-boot-starter-websocket第二步,创建WebSocket配置类importorg.springframework.context.annotation.Bean;importorg.springframework.context.annotation.Configurati

本文目录

    Spring Boot端

    第一步,引入依赖

    首先我们需要引入WebSocket所需的依赖,以及处理输出格式的依赖

    
    
    
       com.alibaba
       fastjson
       1.2.73
    
    
    
        org.springframework.boot
        spring-boot-starter-websocket
    

    第二步,创建WebSocket配置类

    import org.springframework.context.annotation.Bean;
    import org.springframework.context.annotation.Configuration;
    import org.springframework.web.socket.server.standard.ServerEndpointExporter;
     
    /**
     * @author: tjp
     * @create: 2023-04-03 09:58
     * @Description: WebSocket配置
     */
    @Configuration
    public class WebSocketConfig {
        @Bean
        public ServerEndpointExporter serverEndpointExporter() {
            return new ServerEndpointExporter();
        }
     
    }

    第三步,创建WebSocket服务

    这一步我们通过userId作为标识符,区分系统中对应的用户,后续也可基于此,进行其他的操作步骤。

    import com.alibaba.fastjson.JSON;
    import com.alibaba.fastjson.JSONObject;
    import com.alibaba.excel.util.StringUtils;
    import lombok.extern.slf4j.Slf4j;
    import org.springframework.stereotype.Component;
     
    import javax.websocket.*;
    import javax.websocket.server.PathParam;
    import javax.websocket.server.ServerEndpoint;
    import java.io.IOException;
    import java.util.HashMap;
    import java.util.Iterator;
    import java.util.concurrent.ConcurrentHashMap;
     
    /**
     * @author: tjp
     * @create: 2023-04-03 13:55
     * @Description: WebSocket服务
     */
     
    @ServerEndpoint("/websocket/{userId}")
    @Slf4j
    @Component
    public class WebSocketServer {
        /**
         * 静态变量,用来记录当前在线连接数。应该把它设计成线程安全的。
         */
        private static int onlineCount = 0;
        /**
         * concurrent包的线程安全Set,用来存放每个客户端对应的MyWebSocket对象。
         */
        private static ConcurrentHashMap webSocketMap = new ConcurrentHashMap<>();
        /**
         * 与某个客户端的连接会话,需要通过它来给客户端发送数据
         */
        private Session session;
        /**
         * 接收userId
         */
        private String userId = "";
     
        /**
         * 连接建立成功调用的方法
         */
        @OnOpen
        public void onOpen(Session session, @PathParam("userId") String userId) {
            this.session = session;
            this.userId = userId;
            if (webSocketMap.containsKey(userId)) {
                webSocketMap.remove(userId);
                //加入set中
            } else {
                webSocketMap.put(userId, this);
                //加入set中
                addOnlineCount();
                //在线数加1
            }
     
            log.info("用户连接:" + userId + ",当前在线人数为:" + getOnlineCount());
     
            try {
                HashMap map = new HashMap<>();
                map.put("key", "连接成功");
                sendMessage(JSON.toJSONString(map));
            } catch (IOException e) {
                log.error("用户:" + userId + ",网络异常!!!!!!");
            }
        }
     
     
        /**
         * 连接关闭调用的方法
         */
        @OnClose
        public void onClose() {
            if (webSocketMap.containsKey(userId)) {
                webSocketMap.remove(userId);
                //从set中删除
                subOnlineCount();
            }
            log.info("用户退出:" + userId + ",当前在线人数为:" + getOnlineCount());
        }
     
        /**
         * 收到客户端消息后调用的方法
         *
         * @param message 客户端发送过来的消息
         */
        @OnMessage
        public void onMessage(String message, Session session) {
            log.info("用户消息:" + userId + ",报文:" + message);
            //可以群发消息
            //消息保存到数据库、redis
            if (StringUtils.isNotBlank(message)) {
                try {
                    //解析发送的报文
                    JSONObject jsonObject = JSONObject.parseObject(message);
                    //追加发送人(防止串改)
                    jsonObject.put("fromUserId", this.userId);
                    String fromUserId = jsonObject.getString("fromUserId");
                    //传送给对应toUserId用户的websocket
                    if (StringUtils.isNotBlank(fromUserId) && webSocketMap.containsKey(fromUserId)) {
                        webSocketMap.get(fromUserId).sendMessage(jsonObject.toJSONString());
                        //自定义-业务处理
     
    //                    DeviceLocalThread.paramData.put(jsonObject.getString("group"),jsonObject.toJSONString());
                    } else {
                        log.error("请求的userId:" + fromUserId + "不在该服务器上");
                        //否则不在这个服务器上,发送到mysql或者redis
                    }
                } catch (Exception e) {
                    e.printStackTrace();
                }
            }
        }
     
        /**
         * 发生错误时候
         *
         * @param session
         * @param error
         */
        @OnError
        public void onError(Session session, Throwable error) {
            log.error("用户错误:" + this.userId + ",原因:" + error.getMessage());
            error.printStackTrace();
        }
     
        /**
         * 实现服务器主动推送
         */
        public void sendMessage(String message) throws IOException {
            //加入线程锁
            synchronized (session) {
                try {
                    //同步发送信息
                    this.session.getBasicRemote().sendText(message);
                } catch (IOException e) {
                    log.error("服务器推送失败:" + e.getMessage());
                }
            }
        }
     
     
        /**
         * 发送自定义消息
         * */
        /**
         * 发送自定义消息
         *
         * @param message  发送的信息
         * @param toUserId 如果为null默认发送所有
         * @throws IOException
         */
        public static void sendInfo(String message, String toUserId) throws IOException {
            //如果userId为空,向所有群体发送
            if (StringUtils.isEmpty(toUserId)) {
                //向所有用户发送信息
                Iterator itera = webSocketMap.keySet().iterator();
                while (itera.hasNext()) {
                    String keys = itera.next();
                    WebSocketServer item = webSocketMap.get(keys);
                    item.sendMessage(message);
                }
            }
            //如果不为空,则发送指定用户信息
            else if (webSocketMap.containsKey(toUserId)) {
                WebSocketServer item = webSocketMap.get(toUserId);
                item.sendMessage(message);
            } else {
                log.error("请求的userId:" + toUserId + "不在该服务器上");
            }
        }
     
        public static synchronized int getOnlineCount() {
            return onlineCount;
        }
     
        public static synchronized void addOnlineCount() {
            WebSocketServer.onlineCount++;
        }
     
        public static synchronized void subOnlineCount() {
            WebSocketServer.onlineCount--;
        }
     
        public static synchronized ConcurrentHashMap getWebSocketMap() {
            return WebSocketServer.webSocketMap;
        }
     
    }

    第四步,创建Controller进行发送测试

    获取当前在线人数

    import com.......WebSocketServer;
     
    @ApiOperation(value = "获取当前在线人数")
    @GetMapping("/getOnlineCount")
    public Integer getOnlineCount() {
        return WebSocketServer.getOnlineCount();
    }

    通过接口,向前端用户推送消息

    import com.......WebSocketServer;
    import org.springframework.web.bind.annotation.GetMapping;
    import org.springframework.web.bind.annotation.RequestMapping;
    import org.springframework.web.bind.annotation.RestController;
     
    import java.io.IOException;
     
    /**
     * @author: tjp
     * @create: 2023-04-03 13:57
     * @Description: 测试
     */
    @RestController
    @RequestMapping("/news")
    public class NewsController {
        @GetMapping("/send")
        public String send() {
            try {
                WebSocketServer.sendInfo("这是websocket发送过来的消息!", "需要推送的用户的编号");
            } catch (IOException e) {
                throw new RuntimeException(e);
            }
            return "发送消息成功";
        }
     
    }

    Vue端

    第一步,创建连接工具类

    创建工具类websocket.js,这里的userId就是用来作为标识符的userId

    /**
     * @author: tjp
     * @create: 2023-04-03 11:22
     * @Description: Socket客户端
     */
    export class WebSocketClient {
      constructor(userId) {
        this.userId = userId;
        this.websocket = null;
        this.timeout = 10000; // 心跳超时时间,单位ms
        this.timeoutObj = null; // 心跳定时器
        this.serverTimeoutObj = null; // 服务器超时定时器
        this.lockReconnect = false; // 避免重复连接
        this.timeoutnum = null; // 重连延迟定时器
      }
     
      // 初始化WebSocket连接
      initWebSocket() {
        let wsUrl = `ws://127.0.0.1:8080/websocket/${this.userId}`;
        this.websocket = new WebSocket(wsUrl);
        this.websocket.onopen = this.websocketonopen.bind(this);
        this.websocket.onerror = this.websocketonerror.bind(this);
        this.websocket.onmessage = this.setOnmessageMessage.bind(this);
        this.websocket.onclose = this.websocketclose.bind(this);
        // 监听窗口关闭事件,当窗口关闭时,主动去关闭websocket连接,防止连接还没断开就关闭窗口,server端会抛异常。
        window.onbeforeunload = this.websocketclose.bind(this);
      }
     
      // 启动心跳
      start() {
        console.log('start');
        // 清除延时器
        this.timeoutObj && clearTimeout(this.timeoutObj);
        this.serverTimeoutObj && clearTimeout(this.serverTimeoutObj);
        /*// 向服务器发送心跳消息
        let actions = { "test": "12345" };
        this.websocket && this.websocket.readyState == 1 && this.websocket.send(JSON.stringify(actions));
        // 启动心跳定时器
        this.timeoutObj = setTimeout(() => {
          this.start();
          // 定义一个延时器等待服务器响应,若超时,则关闭连接,重新请求server建立socket连接
          this.serverTimeoutObj = setTimeout(() => {
            this.websocket.close();
          }, this.timeout)
        }, this.timeout)*/
      }
     
      // 重置心跳
      reset() {
        // 清除时间
        clearTimeout(this.timeoutObj);
        clearTimeout(this.serverTimeoutObj);
        // 重启心跳
        this.start();
      }
     
      // 重新连接
      reconnect() {
        if (this.lockReconnect) return;
        this.lockReconnect = true;
        // 没连接上会一直重连,设置延迟避免请求过多
        this.timeoutnum && clearTimeout(this.timeoutnum);
        this.timeoutnum = setTimeout(() => {
          this.initWebSocket();
          this.lockReconnect = false;
        }, 5000)
      }
     
      // 处理收到的消息
      async setOnmessageMessage(event) {
        console.log(event.data, '获得消息');
        // 重置心跳
        // this.reset();
        // 自定义全局监听事件
        window.dispatchEvent(new CustomEvent('onmessageWS', {
          detail: {
            data: event.data
          }
        }))
        // //发现消息进入    开始处理前端触发逻辑
        // if (event.data === 'success' || event.data === 'heartBath') return
      }
     
      // WebSocket连接成功回调
      websocketonopen() {
        // 开启心跳
        this.start();
        console.log("WebSocket连接成功!!!" + new Date() + "----" + this.websocket.readyState);
        clearInterval(this.otimer);//停止
      }
     
      // WebSocket连接错误回调
      websocketonerror(e) {
        console.log("WebSocket连接发生错误" + e);
      }
     
      // WebSocket连接关闭回调
      websocketclose(e) {
        this.websocket.close();
        clearTimeout(this.timeoutObj);
        clearTimeout(this.serverTimeoutObj);
        console.log("websocketcloe关闭连接")
      }
     
      // 关闭WebSocket连接
      closeWebSocket() {
        this.websocket.close();
        console.log("closeWebSocket关闭连接")
      }
     
      // 监听窗口关闭事件
      onbeforeunload() {
        this.closeWebSocket();
      }
    }

    第二步,建立连接

    在任意你想建立连接的页面中建立Socket连接

    比如,在用户点击登录按钮之后

    在这里可以使用原型,创建连接对象,并启动连接

    怎么使用Spring Boot+Vue实现Socket通知推送

    第三步,监听服务器发送过来的消息

    在你想监听的页面,使用监听器进行监听

    这个时候,你就可以通过后端的接口进行发送了

     搞个测试

    怎么使用Spring Boot+Vue实现Socket通知推送

    怎么使用Spring Boot+Vue实现Socket通知推送

    第四步,关闭连接 

    搞个按钮

    
     
    

    怎么使用Spring Boot+Vue实现Socket通知推送

    本站声明:本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系bd@zhengruan.com
    作者最新文章
    编程开发 VUE
    相关文章 更多
    精品专题 更多
    装机必备

    正软商城装机必备专区,精选办公、浏览器、安全防护、影音播放、压缩解压、设计创作和系统工具等电脑常用正版软件,帮助用户快速完成新电脑软件配置。

    Windows

    正软商城Windows软件专区,汇集适用于Windows电脑的办公、设计、安全防护、影音播放、开发工具和系统优化软件,提供软件介绍、系统要求、正版授权及购买下载服务。

    PDF教程

    正软商城PDF教程频道提供PDF编辑、转换、合并、拆分、压缩及格式处理方法,同时介绍常用PDF软件和工具的使用技巧。

    macOS软件

    正软商城macOS软件专区,精选适用于Mac电脑的办公、设计、影音、效率、开发和系统工具,提供软件功能介绍、macOS兼容版本、正版授权及购买下载服务。

    IOS软件

    正软商城iOS软件专区,精选适用于iPhone和iPad的办公、学习、影音、设计、效率及AI应用,提供功能介绍、适用设备、系统要求和正版获取方式等信息。

    AI

    正软商城AI软件专区,汇集AI写作、AI绘画、AI视频、AI办公、AI编程、AI翻译、智能客服和数据分析等人工智能工具,提供功能介绍、适用平台、收费方式及正版购买信息。

    Mac软件 更多
    Postman macOS版
    Postman macOS版

    Postman是一套面向API全生命周期的开发与测试平台,可在Mac上发送和调试多种协议请求,管理集合、环境及认证信息,并完成脚本测试、模拟服务、监控、文档发布和团队协作。它适合开发、测试及运维人员使用,提供个人免费方案。

    Docker Desktop macOS版
    Docker Desktop macOS版

    Docker Desktop 是 Docker 官方为 Mac 提供的容器开发环境,集成 Docker Engine、命令行工具、Compose、Build、Kubernetes 与图形化管理界面。

    Android Studio macOS版
    Android Studio macOS版

    Android Studio 是 Google 面向安卓应用开发提供的官方集成开发环境,基于 IntelliJ IDEA 构建。它整合智能代码编辑、Gradle 构建、界面预览、设备模拟、性能分析、调试测试及 APK 分析等工具。

    Xcode macOS版
    Xcode macOS版

    Xcode 是苹果面向 Mac 提供的官方集成开发环境,将代码编辑、项目构建、SwiftUI 实时预览、设备模拟、自动化测试、断点调试、性能分析和应用分发整合在同一套工作流中,适合开发与维护 iPhone、iPad、Mac、Apple Wa

    JetBrains WebStorm macOS版
    JetBrains WebStorm macOS版

    JetBrains WebStorm 是面向 JavaScript、TypeScript 和现代 Web 技术的专业集成开发环境,可智能理解项目结构,提供代码补全、重构、错误检查、运行调试、测试及 Git 工具。

    PhpStorm macOS版
    PhpStorm macOS版

    PhpStorm 是 JetBrains 推出的专业 PHP 集成开发环境,可在 Mac 上完成代码编写、智能检查、重构、调试、测试和数据库管理。它支持主流 PHP 框架、Composer、Git、Docker 与远程解释器。

    JetBrains PyCharm macOS版
    JetBrains PyCharm macOS版

    JetBrains PyCharm 是面向 Python 开发者的集成开发环境,提供智能补全、代码检查、重构、调试、测试、版本控制及虚拟环境管理功能。Mac 版兼容 Intel 与 Apple 芯片,核心功能可免费使用。

    JetBrains IntelliJ IDEA macOS版
    JetBrains IntelliJ IDEA macOS版

    IntelliJ IDEA 是 JetBrains 推出的专业集成开发环境,重点服务于 Java、Kotlin 与 JVM 项目开发。软件集成代码补全、静态检查、重构、调试、测试、版本控制及构建工具,并可借助插件扩展语言和框架支持。

    Visual Studio Code macOS版
    Visual Studio Code macOS版

    Visual Studio Code 是微软提供的免费代码编辑器,支持 macOS,并为 Intel 与 Apple 芯片 Mac 提供适配版本。软件集代码编辑、调试、Git 源代码管理、集成终端和扩展市场于一体。

    REAPER macOS版
    REAPER macOS版

    REAPER是Cockos开发的数字音频工作站,提供多轨音频与MIDI录制、剪辑、处理、混音和母带制作工具。Mac版兼容Intel与Apple芯片,支持AU、VST、VST3、CLAP等插件格式,并提供高度可定制的工作流程。

    Adobe Audition macOS版
    Adobe Audition macOS版

    Adobe Audition 是面向播客、影视后期、音乐制作及内容创作者的专业音频工作站,提供波形精修、多轨录制与混音、频谱编辑、降噪修复、响度匹配和效果处理工具,并可与 Adobe Premiere 协同完成视频声音制作。

    Pro Tools macOS版
    Pro Tools macOS版

    Pro Tools 是 Avid 推出的专业数字音频工作站,覆盖多轨录音、无损剪辑、MIDI 编曲、插件处理、自动化混音及声音与画面同步等工作。它拥有 Intro、Artist、Studio 和 Ultimate 等方案。

    WINDOWS 更多
    PixPix 网页版
    PixPix 网页版

    PixPix 是面向品牌、卖家和内容团队的在线 AI 图片视频创作平台,提供图视频 Agent、无限画布、图片生成、视频生成、自然语言编辑及商品套图、产品精修和带货视频等电商工具。

    Postman Windows版
    Postman Windows版

    Postman 是面向 API 全生命周期的开发与协作平台。Windows 桌面版可用于构建和发送 HTTP、GraphQL、gRPC、WebSocket、MQTT 等请求,并提供环境变量、集合、脚本测试、模拟服务、监控、文档及团队工作区等

    Docker Desktop Windows版
    Docker Desktop Windows版

    Docker Desktop 为 Windows 开发者提供集成式容器环境,内置 Docker Engine、命令行工具、Compose、Build 与 Kubernetes 等组件,可在本机完成镜像构建、容器运行、日志查看和资源管理。

    Android Studio Windows版
    Android Studio Windows版

    Android Studio 是 Google 面向 Android 应用开发提供的官方集成开发环境,以 IntelliJ IDEA 为基础,集成智能代码编辑、Gradle 构建、设备模拟、界面预览、调试测试及性能分析工具,

    JetBrains WebStorm Windows版
    JetBrains WebStorm Windows版

    WebStorm 是 JetBrains 面向 JavaScript、TypeScript 和现代 Web 技术打造的集成开发环境。它提供项目级代码分析、智能补全、安全重构、导航搜索,并集成调试、测试、终端、Git 与常用前端工具,

    JetBrains PhpStorm Windows版
    JetBrains PhpStorm Windows版

    PhpStorm 是 JetBrains 面向 PHP 与现代 Web 开发打造的专业集成开发环境,提供代码补全、静态检查、重构、调试、测试、数据库、版本控制及前端语言支持。Windows 用户可直接下载安装程序,

    JetBrains PyCharm Windows版
    JetBrains PyCharm Windows版

    PyCharm 是 JetBrains 推出的 Python 集成开发环境,提供智能代码补全、错误检查、重构、调试、测试、Git、终端及 Jupyter Notebook 支持。统一版安装后可体验 30 天 Pro 功能,

    JetBrains IntelliJ IDEA Windows版
    JetBrains IntelliJ IDEA Windows版

    JetBrains IntelliJ IDEA 是以 Java、Kotlin 和 JVM 项目为核心的专业集成开发环境,提供智能补全、代码检查、安全重构、调试、测试、版本控制及构建工具集成。统一发行版的核心功能可免费用于商业和非商业项目,

    Visual Studio Code Windows版
    Visual Studio Code Windows版

    Visual Studio Code 是微软推出的免费代码编辑器,Windows 版集成智能补全、代码导航、调试、终端和版本控制,并可通过扩展添加语言、格式化及远程开发能力。它启动较快、配置灵活,

    REAPER Windows版
    REAPER Windows版

    REAPER 是 Cockos 推出的数字音频工作站,适用于录音、MIDI 编曲、音频编辑、混音、母带制作及声音设计。软件安装包小巧,支持多轨录制、灵活路由、自动化、第三方插件和脚本扩展,并提供完整功能的 60 天免费评估期。

    Adobe Audition Windows版
    Adobe Audition Windows版

    Adobe Audition 是面向播客、影视后期、广播与音乐制作的专业音频工作站,提供波形编辑、多轨混音、频谱分析、录音、降噪修复和效果处理等功能。Windows 版通过 Adobe Creative Cloud 安装和管理,

    Pro Tools Windows版
    Pro Tools Windows版

    Pro Tools 是 Avid 推出的专业数字音频工作站,提供多轨录音、音频剪辑、MIDI编曲、插件处理、自动化混音及影视声音制作能力。它适合音乐人、录音师、制作人和音频后期团队使用,并提供免费入门版、订阅方案及永久授权选择。