java后端+前端使用WebSocket实现消息推送

news2025/2/27 14:31:40

java后端+前端使用WebSocket实现消息推送(流程+详细代码)

  • 创建WebSocket的简单实例操作流程
    • 1.引入Websocket依赖
    • 2.创建配置类WebSocketConfig
    • 3.创建WebSocketServer
    • 4.websocket调用
    • 前端WebSocket连接
    • OK,下课!!!

在项目的开发时,遇到实现服务器主动发送数据到前端页面的功能的需求。实现该功能不外乎使用轮询和websocket技术,但在考虑到实时性和资源损耗后,最后决定使用websocket。现在就记录一下用Java实现Websocket技术吧~
    Java实现Websocket通常有两种方式:1、创建WebSocketServer类,里面包含open、close、message、error等方法;2、利用Springboot提供的webSocketHandler类,创建其子类并重写方法。我们项目虽然使用Springboot框架,不过仍采用了第一种方法实现。

创建WebSocket的简单实例操作流程

1.引入Websocket依赖

<!-- https://mvnrepository.com/artifact/org.springframework.boot/spring-boot-starter-websocket -->
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-websocket</artifactId>
            <version>2.7.0</version>
        </dependency>

2.创建配置类WebSocketConfig

import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.web.socket.server.standard.ServerEndpointExporter;

/**
 * 开启WebSocket支持
 */
@Configuration
public class WebSocketConfig {
    @Bean
    public ServerEndpointExporter serverEndpointExporter() {
        return new ServerEndpointExporter();
    }
}

3.创建WebSocketServer

在websocket协议下,后端服务器相当于ws里面的客户端,需要用@ServerEndpoint指定访问路径,并使用@Component注入容器

@ServerEndpoint:当ServerEndpointExporter类通过Spring配置进行声明并被使用,它将会去扫描带有@ServerEndpoint注解的类。被注解的类将被注册成为一个WebSocket端点。所有的配置项都在这个注解的属性中
( 如:@ServerEndpoint(“/ws”) )

下面的栗子中@ServerEndpoint指定访问路径中包含sid,这个是用于区分每个页面


import com.alibaba.fastjson.JSONObject;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Component;
import org.springframework.util.StringUtils;
import javax.websocket.*;
import javax.websocket.server.PathParam;
import javax.websocket.server.ServerEndpoint;
import java.io.IOException;
import java.net.Socket;
import java.util.*;
import java.util.concurrent.ConcurrentHashMap;

/**
 * @ServerEndpoint 注解是一个类层次的注解,它的功能主要是将目前的类定义成一个websocket服务器端,
 * 注解的值将被用于监听用户连接的终端访问URL地址,客户端可以通过这个URL来连接到WebSocket服务器端
 */
@ServerEndpoint("/notice/{userId}")
@Component
@Slf4j
public class NoticeWebsocket {

    //记录连接的客户端
    public static Map<String, Session> clients = new ConcurrentHashMap<>();

    /**
     * userId关联sid(解决同一用户id,在多个web端连接的问题)
     */
    public static Map<String, Set<String>> conns = new ConcurrentHashMap<>();

    private String sid = null;

    private String userId;


    /**
     * 连接成功后调用的方法
     * @param session
     * @param userId
     */
    @OnOpen
    public void onOpen(Session session, @PathParam("userId") String userId) {
        this.sid = UUID.randomUUID().toString();
        this.userId = userId;
        clients.put(this.sid, session);

        Set<String> clientSet = conns.get(userId);
        if (clientSet==null){
            clientSet = new HashSet<>();
            conns.put(userId,clientSet);
        }
        clientSet.add(this.sid);
        log.info(this.sid + "连接开启!");
    }

    /**
     * 连接关闭调用的方法
     */
    @OnClose
    public void onClose() {
        log.info(this.sid + "连接断开!");
        clients.remove(this.sid);
    }

    /**
     * 判断是否连接的方法
     * @return
     */
    public static boolean isServerClose() {
        if (NoticeWebsocket.clients.values().size() == 0) {
            log.info("已断开");
            return true;
        }else {
            log.info("已连接");
            return false;
        }
    }

    /**
     * 发送给所有用户
     * @param noticeType
     */
    public static void sendMessage(String noticeType){
        NoticeWebsocketResp noticeWebsocketResp = new NoticeWebsocketResp();
        noticeWebsocketResp.setNoticeType(noticeType);
        sendMessage(noticeWebsocketResp);
    }


    /**
     * 发送给所有用户
     * @param noticeWebsocketResp
     */
    public static void sendMessage(NoticeWebsocketResp noticeWebsocketResp){
        String message = JSONObject.toJSONString(noticeWebsocketResp);
        for (Session session1 : NoticeWebsocket.clients.values()) {
            try {
                session1.getBasicRemote().sendText(message);
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
    }

    /**
     * 根据用户id发送给某一个用户
     * **/
    public static void sendMessageByUserId(String userId, NoticeWebsocketResp noticeWebsocketResp) {
        if (!StringUtils.isEmpty(userId)) {
            String message = JSONObject.toJSONString(noticeWebsocketResp);
            Set<String> clientSet = conns.get(userId);
            if (clientSet != null) {
                Iterator<String> iterator = clientSet.iterator();
                while (iterator.hasNext()) {
                    String sid = iterator.next();
                    Session session = clients.get(sid);
                    if (session != null) {
                        try {
                            session.getBasicRemote().sendText(message);
                        } catch (IOException e) {
                            e.printStackTrace();
                        }
                    }
                }
            }
        }
    }

    /**
     * 收到客户端消息后调用的方法
     * @param message
     * @param session
     */
    @OnMessage
    public void onMessage(String message, Session session) {
        log.info("收到来自窗口"+this.userId+"的信息:"+message);
    }

    /**
     * 发生错误时的回调函数
     * @param error
     */
    @OnError
    public void onError(Throwable error) {
        log.info("错误");
        error.printStackTrace();
    }

}

封装了一个发送消息的对象可以直接使用

import io.swagger.annotations.ApiModel;
import io.swagger.annotations.ApiModelProperty;
import lombok.Data;

@Data
@ApiModel("ws通知返回对象")
public class NoticeWebsocketResp<T> {

    @ApiModelProperty(value = "通知类型")
    private String noticeType;

    @ApiModelProperty(value = "通知内容")
    private T noticeInfo;

}

4.websocket调用

一个用户调用接口,主动将信息发给后端,后端接收后再主动推送给指定/全部用户


@RestController
@RequestMapping("/order")
public class OrderController {
	@GetMapping("/test")
    public R test() {
    	NoticeWebsocket.sendMessage("你好,WebSocket");
        return R.ok();
    }
}

前端WebSocket连接

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>SseEmitter</title>
</head>
<body>
<div id="message"></div>
</body>
<script>
var limitConnect = 0;
init();
function init() {
var ws = new WebSocket('ws://192.168.2.88:9060/notice/1');
// 获取连接状态
console.log('ws连接状态:' + ws.readyState);
//监听是否连接成功
ws.onopen = function () {
    console.log('ws连接状态:' + ws.readyState);
    limitConnect = 0;
    //连接成功则发送一个数据
    ws.send('我们建立连接啦');
}
// 接听服务器发回的信息并处理展示
ws.onmessage = function (data) {
    console.log('接收到来自服务器的消息:');
    console.log(data);
    //完成通信后关闭WebSocket连接
    // ws.close();
}
// 监听连接关闭事件
ws.onclose = function () {
    // 监听整个过程中websocket的状态
    console.log('ws连接状态:' + ws.readyState);
reconnect();

}
// 监听并处理error事件
ws.onerror = function (error) {
    console.log(error);
}
}
function reconnect() {
    limitConnect ++;
    console.log("重连第" + limitConnect + "次");
    setTimeout(function(){
        init();
    },2000);
   
}
</script>
</html>

项目启动,打开页面后控制台打印连接信息
在这里插入图片描述
调用order/test方法后前端打印推送消息内容
在这里插入图片描述
这样,就可以接口或者ws调用网址的方式进行websocket的通信啦~
如果没有前端页面也可以使用在线WebSocket测试
在这里插入图片描述

OK,下课!!!

本文来自互联网用户投稿,该文观点仅代表作者本人,不代表本站立场。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如若转载,请注明出处:http://www.coloradmin.cn/o/405192.html

如若内容造成侵权/违法违规/事实不符,请联系多彩编程网进行投诉反馈,一经查实,立即删除!

相关文章

【uploader】表格化自整理vue-simple-uploader的文档(超详细)

文章目录1.vue-simple-uploader介绍2.安装和配置3. 组件标签的文档整理3.1 uploader标签3.2 uploader-btn标签3.3 uploader-drop标签3.4 uploader-list标签3.5 uploader-file标签3.6 uploader-unsopport标签4.请求中的参数轮子的github链接&#xff1a;两个项目的文档要结合着看…

HTML可用于情侣表白的爱心代码~,赶紧跟着操作,让她也拥有属于你的爱心吧。

文章目录前言一、效果图二、操作步骤第一步第二步第三步第四步第五步第六步源码前言 最近随着电视剧《点燃我温暖你》的火热播出&#xff0c;剧中帅气学霸李洵的炫酷爱心代码也迅速火出了圈&#xff0c;爱心素材也异常火爆&#xff0c;我在这里整理了一份大家有需自取哦~ 可用于…

【React Router 6 快速上手一】重定向Navigate / useRoutes路由表 / 嵌套路由Outlet

前言 博主主页&#x1f449;&#x1f3fb;蜡笔雏田学代码 专栏链接&#x1f449;&#x1f3fb;React专栏 之前学习了react-router-dom5版本的相关内容 参考文章&#x1f449;&#x1f3fb;React路由&#xff08;详解版&#xff09;和 路由的模糊匹配&#xff0c;重定向以及嵌套…

vue安装及环境配置

目录 1.安装 Node.js 2.配置默认安装目录和缓存日志目录 3.配置环境变量 4.配置淘宝镜像 5.安装vue和脚手架 6.创建并运行项目 1.安装 Node.js Download | Node.js 在这里&#x1f446;下载的是最新版&#xff0c;如果要安装以前的版本&#x1f447;&#xff0c;页面往下…

3分钟让你学会axios在vue项目中的基本用法(建议收藏)

Axios酸狗来教你 提示&#xff1a;本篇详解axios在vue项目中的实例。在使用Vue.js框架开发前端项目时&#xff0c;会经常发送ajax请求服务端接口&#xff0c;在开发过程中&#xff0c;需要对axios进一步封装&#xff0c;方便在项目中的使用。 文章目录Axios酸狗来教你Axios简介…

JavaScript之正则表达式的使用方法详细介绍

目录 I. 序言&#xff1a;JavaScript中正则表达式的使用场景 II. 创建第一个正则表达式 III. 常见的正则表达式属性 &#x1f4d5; 三种匹配规则 &#x1f4d5; 五种常见属性 &#x1f4d5; 规则g的使用详解 IV. 常见的正则表达式方法举例介绍 &#x1f4d8; test方法 …

idea构建web项目-超详细教程

1、idea构建web项目 idea构建web项目的超级详细教程&#xff0c;一步一步来&#xff0c;完全没问题&#xff01; 1、新建一个空项目 2、新建java模块&#xff0c;名为webDemo1 3、选择webDemo1右键&#xff0c;选择Add Framework Support 选择Web Application 4、在WEB-…

Geeker-Admin项目跟做笔记(vue3+vite+pinia)

文章目录一、路由配置&#xff08;一&#xff09; 静态路由&#xff08;二&#xff09;动态路由二、axios的配置1. 创建axiosCancel.ts文件&#xff0c;用于有pending后直接取消2. axios封装3. 使用三、pinia仓库的使用四、Header 设计笔记1. 国际化&#xff08;中英文切换&…

【小程序开发】—— 封装自定义弹窗组件

文章目录&#x1f34b;前言&#xff1a;&#x1f34d;正文1、探讨需求封装popup自定义弹窗组件2、实战开发弹窗组件2.1 子组件内容 popup.vue文件2.2 父组件引用子组件3、效果图预览3.1 不使用具名插槽的原有样式效果3.2 使用具名插槽之后样式效果&#x1f383;专栏分享&#x…

快速掌握Nginx部署前端项目(从Nginx安装配置及部署都非常详细哦!)

前言&#xff1a; 之前在Linux系统中部署了后端项目&#xff0c;今天继续来给大家分享如何部署前端项目。 涉及到了Nginx的简单介绍以及Nginx如何安装及配置并且能够部署前端项目 Nginx是一个轻量级的反向代理web服务器&#xff0c;在当今应用地非常广泛&#xff0c;特别是前…

vue的proxy代理详解

一、proxy常用参数说明 module.exports {publicPath: "/",devServer: {proxy: {"/api": {// 代理名称 凡是使用/api开头的地址都是用此代理target: "http://1.2.3.4:5000/", // 需要代理访问的api地址changeOrigin: true, // 允许跨域请求pa…

[Node.js]如何在IDEA中配置Node.js

【目录】 一、下载Node.js 二、安装Node.js 三、配置Node.js 四、测试Node.js 一、下载Node.js 官网下载链接&#xff1a;Node.js 点击下图红色标注区域&#xff0c;即可下载msi文件 二、安装Node.js 打开msi文件 一路点击“Next”&#xff08;建议自定义文件安装路径&#xf…

vue3的基本使用(超详细)

一、初识vue3 1.vue3简介 2020年9月18日&#xff0c;vue3发布3.0版本&#xff0c;代号大海贼时代来临&#xff0c;One Piece特点&#xff1a; 无需构建步骤&#xff0c;渐进式增强静态的 HTML在任何页面中作为 Web Components 嵌入单页应用 (SPA)全栈 / 服务端渲染 (SSR)Jams…

使用小程序制作一个电子木鱼,功德+1

此文主要通过小程序制作一个敲木鱼的小工具,在心烦意乱的时候缓解一下焦虑。 一、创建小程序二、设计页面三、代码块一、创建小程序 访问微信公众平台,点击账号注册。选择小程序,并在表单填写所需的各项信息进行注册。在开发管理选择开发设置,将AppID及AppSecret复制出来进…

Vue路由导航报错:NavigationDuplicated: Avoided redundant navigation to current location解决方法

点击vue路由跳转&#xff0c;控制台报错&#xff1a;Avoided redundant navigation to current location: “/xxxxxx“解决方法 一、描述问题 在使用this.$router.push跳转页面时候&#xff0c;重复点击菜单引起路由重复报错 比如当前页面显示区是路由组件‘/cats’&#xff…

关于js 中 try catch用法

try…catch语法&#xff0c;简单来说就是用来捕获异常的&#xff0c;我就简述一下我遇到的问题 当使用vuex在actions发请求时&#xff0c;这个接口不仅可以添加购物车数据&#xff0c;同时也可更新产品的数量&#xff0c;我就在更新产品数量的地方出现了问题&#xff0c; 先说说…

HTML生日快乐-生日祝福(烟花+粒子动画)

本人对前端不太了解&#xff0c;对网上代码进行简单修改&#xff0c;完成部署。 粒子动画&#xff1a;https://github.com/kennethcachia/shape-shifter 烟花&#xff1a;网上有许多相关代码&#xff0c;未找到原作者 效果&#xff1a;http://8.130.106.21/HappyBirthday/Happy…

原生HTML+CSS+JS制作自己的导航主页(前端大作业,源码+步骤详解)

文章目录前言一、插入背景二、头部1.导航栏2. 优化导航栏3 时间4. 搜索框三、主体四、底部五、背景泡沫球特效六、note小便签七、全部代码1. index.html2. style.css3. index.js八、总结链接&#xff1a;https://pan.baidu.com/s/1uaRCJXyIrY56NXabau4wjw?pwdLDL6 提取码&…

Vue3详细教程

一.Vue3的介绍 相信大家都已经学习过Vue2了&#xff0c;对Vue有了一定的了解。那么今天我们就一起来学习有关Vue3的知识点。那为什么要学习Vue3呢&#xff0c;主要是他有以下的特点。 &#xff08;1&#xff09;新增组合式api &#xff08;2&#xff09;更加接近原生 &#xf…

JavaWeb web.xml配置详解

参考&#xff1a; XML 教程Java web之web.xml配置详解 Javaweb三大组件是&#xff1a;Servlet&#xff0c;Filter&#xff0c;Listener。 1、Servlet Servlet作为中转处理的容器&#xff0c;连接了客户端和服务器端的信息交互和处理。2、Filter 拦截用户请求&#xff0c;在服…