当前位置:

首页 > 编程开发 > 怎么使用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
    相关文章 更多
    vue上传文件格式怎么设置及要求说明
    vue上传文件格式怎么设置及要求说明

    学习如何在Vue项目中设置文件上传格式限制。本文介绍使用HTML accept属性进行基础过滤,以及结合JavaScript进行严格后缀名校验的方法,确保只允许指定类型的文件被上传。

    vue创建项目很慢怎么解决及常见原因排查教程
    vue创建项目很慢怎么解决及常见原因排查教程

    分析Vue项目创建缓慢的常见原因,包括网络延迟和依赖下载问题,提供切换镜像源、更换包管理器及使用Vite等具体优化方案,提升开发环境搭建效率。

    vue下载文件怎么做到点上就有反应在浏览器显示进度条
    vue下载文件怎么做到点上就有反应在浏览器显示进度条

    详解如何在Vue项目中利用Axios的onDownloadProgress回调捕获下载进度,并结合UI组件实时渲染进度条,同时分析Blob对象处理大文件时的内存限制与替代方案。

    uniapp网络请求拦截怎么设置方法详细教程
    uniapp网络请求拦截怎么设置方法详细教程

    学习如何在UniApp项目中设置网络请求拦截器,实现统一的Token管理、请求参数处理和响应错误捕获,优化前端开发体验。

    Vue页面空白的排查方法及解决办法
    Vue页面空白的排查方法及解决办法

    遇到Vue项目页面空白不要慌,本文通过路由匹配、组件生命周期、异步数据加载及权限控制四个真实场景,详解排查步骤与解决办法,助你快速恢复页面显示。

    c socket 实际应用案例分享
    c socket 实际应用案例分享

    Socket是网络通信的核心技术,通过客户端-服务器模型实现设备间数据交换,支持构建从基础回声服务到多人聊天室等应用。结合应用层协议可实现文件传输等复杂功能,并在物联网中用于设备数据上报。开发时需处理网络异常并借助工具调试。

    c socket 相关工具怎么挑选更合适
    c socket 相关工具怎么挑选更合适

    选择Socket工具需明确需求:简易工具应界面直观、连接快捷;专业工具需支持脚本与深度解析。评估时需兼顾易用性、协议支持、数据定制、性能及扩展性,同时权衡成本与团队协作,考虑开源或商业软件,并符合团队习惯与安全规范。

    WIFI编程
    WIFI编程

    Wi-Fi编程实质上就是TCP/IP编程,即套接字编程。无需深究Wi-Fi底层原理与协议细节,转向TCP/IP编程书籍即可快速实现可靠通信。相关资料极为丰富,易于获取,大幅降低了学习门槛。掌握套接字编程后,能高效开发各类网络应用。

    Sublime实现一键生成Vue模板_自定义Snippet实战
    Sublime实现一键生成Vue模板_自定义Snippet实战

    在Sublime中为Vue文件自定义Snippet时,scope参数错误是最常见的Tab无响应原因。需通过Developer:ShowScopeName确认正确语法作用域。占位符需依次递增,$0可选但建议添加。相同数字占位符会同步编辑,可通过不同编号解耦。Snippet无法在新建文件时自动展开,需手动输入tabTrigger后按Tab。务必确保文件已正确识别

    VSCode如何解决Prettier和Vue单引号双引号的冲突问题
    VSCode如何解决Prettier和Vue单引号双引号的冲突问题

    在Vue项目中,为解决Prettier默认双引号与Vue单引号规则的冲突,必须在项目根目录创建.prettierrc并设置singleQuote:true。同时VSCode全局设置失效,需依赖项目级配置。此外,需配置Vetur使JS格式化使用Prettier;Vue3项目禁用Vetur启用Volar。最后在ESLint的extends末尾添加eslint-c

    查看更多
    精品专题 更多
    装机必备
    装机必备

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

    Windows
    Windows

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

    PDF教程
    PDF教程

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

    Mac软件 更多
    讯飞智作 网页版
    讯飞智作 网页版
    Windows/ macOS/ Linux

    讯飞智作是一款基于语音合成技术、虚拟人驱动技术与数字人形象声音构建能力的 AI 数字人音视频创作平台。

    火山引擎 网页版
    火山引擎 网页版
    Windows/ macOS/ Linux

    火山引擎是字节跳动旗下企业级云与AI服务平台。聚焦大模型核心能力,依托字节自研豆包多模态大模型,凭借火山方舟一站式平台,提供模型精调、推理部署、智能应用搭建等全链路服务,结合高性能AI算力,助力各行业快速落地大模型数字化与智能化应用。

    Aperty macOS版
    Aperty macOS版
    macOS

    Aperty 是 Skylum 推出的 AI 人像修图软件,支持自然肤质修饰、瑕疵处理、面部与身体调整、预设及批量同步。

    WINDOWS 更多
    讯飞智作 网页版
    讯飞智作 网页版
    Windows/ macOS/ Linux

    讯飞智作是一款基于语音合成技术、虚拟人驱动技术与数字人形象声音构建能力的 AI 数字人音视频创作平台。

    火山引擎 网页版
    火山引擎 网页版
    Windows/ macOS/ Linux

    火山引擎是字节跳动旗下企业级云与AI服务平台。聚焦大模型核心能力,依托字节自研豆包多模态大模型,凭借火山方舟一站式平台,提供模型精调、推理部署、智能应用搭建等全链路服务,结合高性能AI算力,助力各行业快速落地大模型数字化与智能化应用。

    PixTV 网页版
    PixTV 网页版
    Windows

    PixTV 是一款在浏览器中使用的 AI 视觉内容创作平台,提供图片、视频、音频、文字生成、AI 分镜、局部重绘、提示词反推和无限画布等工具,适合短剧、漫剧、广告及社交媒体内容制作。