【Java后端向前端推送消息】

【Java后端向前端推送消息】

1、WebSocketConfig配置类

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.server.standard.ServerEndpointExporter; @Configuration @EnableWebSocket publicclassWebSocketConfig{ @Bean public ServerEndpointExporter serverEndpointExporter(){returnnewServerEndpointExporter();}}

2、WebSocket消息发送接收

import lombok.extern.slf4j.Slf4j;import org.springframework.stereotype.Component;import org.springframework.util.ObjectUtils;import javax.websocket.*;import javax.websocket.server.PathParam;import javax.websocket.server.ServerEndpoint;import java.util.Map;import java.util.Set;import java.util.concurrent.ConcurrentHashMap; @Slf4j @Component @ServerEndpoint(value ="/web/{id}")publicclassWebSocketProcess{/* * 持有每个webSocket对象,以key-value存储到线程安全ConcurrentHashMap, */privatestatic ConcurrentHashMap<Long, WebSocketProcess> concurrentHashMap =newConcurrentHashMap<>(12);/** * 会话对象 **/private Session session;/* * 客户端创建连接时触发 * */ @OnOpen publicvoidonOpen(Session session, @PathParam("id") long id){//每新建立一个连接,就把当前客户id为key,this为value存储到map中this.session = session; concurrentHashMap.put(id,this); log.info("Open a websocket. id={}", id);}/** * 客户端连接关闭时触发 **/ @OnClose publicvoidonClose(Session session, @PathParam("id") long id){//客户端连接关闭时,移除map中存储的键值对 concurrentHashMap.remove(id); log.info("close a websocket, concurrentHashMap remove sessionId= {}", id);}/** * 接收到客户端消息时触发 */ @OnMessage publicvoidonMessage(String message, @PathParam("id") String id){ log.info("receive a message from client id={},msg={}", id, message);}/** * 连接发生异常时候触发 */ @OnError publicvoidonError(Session session, Throwable error){ log.error("Error while websocket. ", error);}/** * 发送消息到指定客户端 * * @param id * @param message */publicvoidsendMessage(long id, String message) throws Exception {//根据id,从map中获取存储的webSocket对象 WebSocketProcess webSocketProcess = concurrentHashMap.get(id);if(!ObjectUtils.isEmpty(webSocketProcess)){//当客户端是Open状态时,才能发送消息if(webSocketProcess.session.isOpen()){ webSocketProcess.session.getBasicRemote().sendText(message);}else{ log.error("websocket session={} is closed ", id);}}else{ log.error("websocket session={} is not exit ", id);}}/** * 发送消息到所有客户端 */publicvoidsendAllMessage(String msg) throws Exception { log.info("online client count={}", concurrentHashMap.size()); Set<Map.Entry<Long, WebSocketProcess>> entries = concurrentHashMap.entrySet();for(Map.Entry<Long, WebSocketProcess> entry : entries){ Long cid = entry.getKey(); WebSocketProcess webSocketProcess = entry.getValue(); boolean sessionOpen = webSocketProcess.session.isOpen();if(sessionOpen){ webSocketProcess.session.getBasicRemote().sendText(msg);}else{ log.info("cid={} is closed,ignore send text", cid);}}}}

3、消息推送Controller

import com.xyl.web.controller.common.WebSocketProcess;import com.xyl.web.controller.common.WebSocketServer;import org.springframework.beans.factory.annotation.Autowired;import org.springframework.scheduling.annotation.Scheduled;import org.springframework.web.bind.annotation.PostMapping;import org.springframework.web.bind.annotation.RequestMapping;import org.springframework.web.bind.annotation.RequestParam;import org.springframework.web.bind.annotation.RestController; @RestController @RequestMapping("/testws")publicclassWebSocketController{/** * 注入WebSocketProcess **/ @Autowired private WebSocketProcess webSocketProcess;/** * 向指定客户端发消息 * * @param id */ @PostMapping(value ="sendMsgToClientById")publicvoidsendMsgToClientById(@RequestParam long id, @RequestParam String text){try{ webSocketProcess.sendMessage(id, text);}catch(Exception e){ e.printStackTrace();}}/** * 发消息到所有客户端 * * @param text */ @PostMapping(value ="sendMsgToAllClient")publicvoidsendMsgToAllClient(@RequestParam String text){try{ webSocketProcess.sendAllMessage(text);}catch(Exception e){ e.printStackTrace();}}/** * 定时向客户端推送消息 * @throws Exception */ @Scheduled(cron ="0/5 * * * * ?")privatevoidconfigureTasks() throws Exception { webSocketProcess.sendAllMessage("向前端推送消息内容");}}

4、测试HTML

<!DOCTYPE html><html><head><meta charset="UTF-8"><title>websocket测试</title><script src="http://code.jquery.com/jquery-2.1.1.min.js"></script></head><body><div id="content"></div></body><script type="text/javascript">$(function(){var ws;//检测浏览器是否支持webSocketif("WebSocket"in window){$("#content").html("您的浏览器支持webSocket!");//模拟产生clientIDlet clientID = Math.ceil(Math.random()*100);//创建 WebSocket 对象,注意请求路径!!!! ws =newWebSocket("ws://127.0.0.1:9095/web/"+clientID);//与服务端建立连接时触发 ws.onopen=function(){$("#content").append("<p>与服务端建立连接建立成功!您的客户端ID="+clientID+"</p>");//模拟发送数据到服务器 ws.send("你好服务端!我是客户端 "+clientID);}//接收到服务端消息时触发 ws.onmessage=function(evt){let received_msg = evt.data;$("#content").append("<p>接收到服务端消息:"+received_msg+"</p>");};//服务端关闭连接时触发 ws.onclose=function(){ console.error("连接已经关闭.....")};}else{$("#content").html("您的浏览器不支持webSocket!");}})</script></html>

Read more

Cursor+Codex隐藏技巧:用截图秒修前端Bug的保姆级教程(React/Chakra UI案例)

Cursor+Codex隐藏技巧:用截图秒修前端Bug的保姆级教程(React/Chakra UI案例) 前端开发中最令人头疼的莫过于那些难以定位的UI问题——元素错位、样式冲突、响应式失效...传统调试方式往往需要反复修改代码、刷新页面、检查元素。现在,通过Cursor编辑器集成的Codex功能,你可以直接用截图交互快速定位和修复这些问题。本文将带你从零开始,掌握这套革命性的调试工作流。 1. 环境准备与基础配置 在开始之前,确保你已经具备以下环境: * Cursor编辑器最新版(v2.5+) * Node.js 18.x及以上版本 * React 18项目(本文以Chakra UI 2.x为例) 首先在Cursor中安装Codex插件: 1. 点击左侧扩展图标 2. 搜索"Codex"并安装 3. 登录你的OpenAI账户(需要ChatGPT Plus订阅) 关键配置项: // 在项目根目录创建.

2025强网杯web wp

文章目录 * secret_value * 1️⃣ 读取代理传来的用户 ID * bbjv * 代码整体分析 * yamcs * ez_php * 日志系统 * CeleRace * PTer 一直想着复现一下把其他几道题看看,结果一拖就拖了这么多天 secret_value ai分析登进去就可以在dashboard处看到flag 但是在访问dashboard前还要经过装饰器函数login_required的检查 def login_required(view_func): @wraps(view_func) def wrapped(*args, **kwargs): uid = request.headers.get('X-User', '0') print(uid) if uid == 'anonymous'

用Coze打造你的专属AI应用:从智能体到Web部署指南

用Coze打造你的专属AI应用:从智能体到Web部署指南

文章目录 * 一、Coze简介 * 1.1 什么是Coze? * 1.2 核心概念 * 二、Coze产品生态 * 三、智能体开发基础 * 四、Coze资源 * 4.1 插件 * 4.2 扣子知识库 * 4.3 数据库资源 * 五、工作流开发与发布 * 六、应用开发与发布 * 七、Coze的API与SDK * 八、实战案例 一、Coze简介 1.1 什么是Coze? Coze 是字节跳动开发的 AI Agent 平台,作为一款人工智能开发工具,它可以帮助开发者通过低代码甚至零代码的方式快速构建应用程序。此外还提供了相关的API和SDK,可以集成到我们自己开发的项目业务中。 1.2 核心概念 * 智能体:

【JWT】JWT(JSON Web Token)结构化知识体系(完整版)

【JWT】JWT(JSON Web Token)结构化知识体系(完整版)

文章目录 * JWT(JSON Web Token) * 一、基础认知层:定义与核心边界 * 1. 核心定义 * 2. 诞生背景 * 3. 适用与不适用场景 * 二、核心结构层:JWT的标准格式与字段规范 * 1. Header(头部) * 2. Payload(载荷) * 3. Signature(签名) * 三、核心原理与标准工作流程 * 1. 核心底层原理 * 2. 标准全流程(前后端分离核心场景) * 四、算法体系与分类规范 * 1. JWT两大分支:JWS vs JWE * 2. JWS核心签名算法 * (1)对称加密算法(HS系列) * (2)非对称加密算法(RS/ES/PS系列)