vue,java,webSocket通讯,服务端主动给多客户端发消息

server/2024/10/25 4:10:31/

vue在那个页面内:

created() {// 可以在created钩子中初始化WebSocket连接this.initWebSocket();},
data: () => {return {webSocket: null, // WebSocket对象},
},
beforeDestroy() {// 组件销毁前关闭WebSocket连接if (this.webSocket) {this.webSocket.close();}
},
methods: {initWebSocket() {// 替换为你的WebSocket服务端地址const wsUrl = "ws://192.168.200.131:8059/clientSocket";this.webSocket = new WebSocket(wsUrl);// 打开连接this.webSocket.onopen = () => {console.log("WebSocket连接已打开");};// 接收消息this.webSocket.onmessage = (event) => {console.log("接收到服务器消息:", event.data);// 处理接收到的数据this.handleData(event.data);};// 连接关闭this.webSocket.onclose = () => {console.log("WebSocket连接已关闭");// 可以在这里实现重连逻辑this.reconnectWebSocket();};// 连接错误this.webSocket.onerror = (error) => {console.error("WebSocket发生错误:", error);};},handleData(data) {// 处理接收到的数据this.onLinePlate_3500Q();this.onLinePlate_3500T();this.onLinePlate_2800Q();this.onLinePlate_2800T();},reconnectWebSocket() {// 实现重连逻辑setTimeout(() => {this.initWebSocket();}, 5000); // 5秒后重连},},

java:
1.pom.xml

 		<dependency><groupId>org.springframework.boot</groupId><artifactId>spring-boot-starter-websocket</artifactId></dependency>

2.启动类application

@Beanpublic ThreadPoolTaskScheduler taskScheduler(){ThreadPoolTaskScheduler taskScheduler = new ThreadPoolTaskScheduler();taskScheduler.setPoolSize(10);taskScheduler.initialize();return taskScheduler;}

在这里插入图片描述

3.新建一个WebSocketConfig.java

package com.alnan.unit.WebSocket;import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Bean;
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;
import org.springframework.web.socket.server.standard.ServerEndpointExporter;/*** @author * @date **/
@Configuration
@EnableWebSocket
//public class WebSocketConfig implements WebSocketConfigurer {
public class WebSocketConfig {//    @Override
//    public void registerWebSocketHandlers(WebSocketHandlerRegistry registry) {
//        registry.addHandler(new WebSocketHandler(), "/clientSocket").setAllowedOrigins("*");
//    }@Beanpublic ServerEndpointExporter serverEndpoint() {return new ServerEndpointExporter();}/*** 注意事项:* WebSocket启动的时候优先于spring容器,从而导致在WebSocketServer中调用业务Service会报空指针异常* 所以需要在WebSocketServer中将所需要用到的service给静态初始化一下* 此处提前注入*/
//    @Autowired
//    private void setXxx(XxxService xxxService) {
//        WebSocketServer.xxxService = xxxService;
//    }
}

4.新建一个WebSocketServer类

package com.alnan.unit.WebSocket;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.concurrent.CopyOnWriteArraySet;/*** @author * @date 2023/11/8* @description: 若在此类中直接调用service方法失败,需要加上:public static XxxService xxxService; 另外在config中注入实例**/
@Slf4j
@Component
@ServerEndpoint(value = "/clientSocket")
public class WebSocketServer {/*** 当前连接数*/private static int onlineCount = 0;/*** concurrent包的线程安全Set,用来存放每个客户端对应的MyWebSocket对象*/private static CopyOnWriteArraySet<WebSocketServer> webSocketSet = new CopyOnWriteArraySet<>();/*** 与某个客户端的连接会话,需要通过它来给客户端发送数据*/private Session session;/*** 接收的用户id*/private String userId;/*** 连接建立成功调用的方法,客户端进来请求这个,并返回*/@OnOpenpublic void onOpen(Session session) {this.session = session;webSocketSet.add(this);addOnlineCount();        //在线数加1log.info("有新连接加入!当前在线人数为" + getOnlineCount());try {sendMessage("连接成功");} catch (IOException e) {log.error("websocket IO异常", e);}}/*** 连接关闭调用的方法*/@OnClosepublic void onClose() {webSocketSet.remove(this);subOnlineCount();               //在线数减1log.info("有一连接关闭!当前在线人数为" + getOnlineCount());}/*** 收到客户端消息后调用的方法** @param message 客户端发送过来的消息*/@OnMessagepublic void onMessage(String message) {log.info("来自客户端的消息:" + message);//群发消息for (WebSocketServer item : webSocketSet) {try {item.sendMessage(message);} catch (IOException e) {log.error("发送消息失败", e);}}}/*** @param error 错误*/@OnErrorpublic void onError( Throwable error) {log.error("发生错误", error);}/*** 发送消息* @param message 消息* @throws IOException 异常*/public void sendMessage(String message) throws IOException {this.session.getBasicRemote().sendText(message);}/*** 群发自定义消息*/public static void sendInfo(String message) {log.info("消息内容:" + message);for (WebSocketServer item : webSocketSet) {try {//这里可以设定只推送给这个sid的,为null则全部推送item.sendMessage(message);} catch (IOException e) {log.error("消息发送失败", e);}}}/*** 获取在线人数* @return 在线人数*/public static synchronized int getOnlineCount() {return onlineCount;}/*** 在线人数加一*/public static synchronized void addOnlineCount() {WebSocketServer.onlineCount++;}/*** 在线人数减一*/public static synchronized void subOnlineCount() {WebSocketServer.onlineCount--;}
}

5.后端调用方法,主动给客户端发消息

  WebSocketServer.sendInfo("dataReload");

在这里插入图片描述


http://www.ppmy.cn/server/134600.html

相关文章

无人机组装、调试车间设计技术详解

无人机组装、调试车间的设计技术需要综合考虑多个方面&#xff0c;以确保生产过程的顺利进行和产品质量的可靠保障。以下是对无人机组装、调试车间设计技术的详细解析&#xff1a; 一、车间布局规划 1. 功能区域划分&#xff1a; 组装区&#xff1a;用于无人机的各个部件的组…

ESP32移植Openharmony设备开发---(6)Mutex互斥锁

Mutex互斥锁 官方文档&#xff1a;OpenAtom OpenHarmony 基本概念 互斥锁又称互斥型信号量&#xff0c;用于实现对共享资源的独占式处理。当有任务持有时&#xff0c;这个任务获得该互斥锁的所有权。当该任务释放它时&#xff0c;任务失去该互斥锁的所有权。当一个任务持有互…

大数据治理:Python实现与案例分析

目录 大数据治理&#xff1a;Python实现与案例分析引言1. 大数据治理的核心概念1.1 数据治理的关键要素1.2 大数据治理的挑战 2. 面向对象的Python大数据治理系统设计2.1 数据治理系统的类设计2.2 代码解释 3. 案例分析案例1&#xff1a;数据标准化案例2&#xff1a;数据质量管…

AI大模型开发架构设计(14)——基于LangChain大模型的案例架构实战

文章目录 基于LangChain大模型的案例架构实战1 LangChain 顶层架构设计以及关键技术剖析LangChain 是什么?LangChain的主要功能是什么&#xff1f;LangChain 顶层架构设计LangChain 典型使用场景&#xff1a;QA 问答系统LangChain 顶层架构设计之 Model I/OLangChain 顶层架构…

在 Spring 框架中,循环依赖是指两个或多个 Bean 之间相互依赖

在 Spring 框架中&#xff0c;循环依赖是指两个或多个 Bean 之间相互依赖&#xff0c;形成一个闭环。例如&#xff0c;Bean A 依赖于 Bean B&#xff0c;而 Bean B 又依赖于 Bean A。这种情况如果不加以处理&#xff0c;会导致 Bean 无法正确实例化&#xff0c;从而引发应用程序…

构建 effet.js 人脸识别交互系统的实战之路

构建 effet.js 人脸识别交互系统的实战之路 文章目录 构建 effet.js 人脸识别交互系统的实战之路前言一、什么是effet.js二、为什么需要使用effet.js四、effet.js能做什么五、使用步骤1.引入库2.main.js中注册全局2.使用3.效果图 六、其他模式讲解人脸打卡人脸添加睡眠检测 在h…

Python实现贪吃蛇大作战

初始版本 初始版本&#xff0c;只存在基本数据结构——双向队列。 游戏思路 贪吃蛇通过不断得吃食物来增长自身&#xff0c;如果贪吃蛇碰到边界或者自身则游戏失败。 食物是绿色矩形来模拟&#xff0c;坐标为随机数生成&#xff0c;定义一个蛇长变量&#xff0c;判断蛇头坐标和…

独孤思维:新学员副业一周出单

所谓的一万小时定律。 即在某个技能上面&#xff0c;花费超过1万小时。 如果每天刻意练习1小时&#xff0c;则需要30年。 可行吗&#xff1f; 极难。 所以不要过分迷恋这种定律。 对于我们普通人而言&#xff0c;可以训练一个月或者三个月&#xff0c;即可掌握某项技能。…