From 3879216b974b6a54232dd03017e0695186cea092 Mon Sep 17 00:00:00 2001 From: ZengTao <2773468879@qq.com> Date: 星期三, 06 九月 2023 17:02:47 +0800 Subject: [PATCH] 更新从后台往前端推送数据 --- springboot-vue3/src/main/java/com/example/springboot/component/WebSocketServer.java | 41 ++++++++++++++++++++++++++++++++++------- 1 files changed, 34 insertions(+), 7 deletions(-) diff --git a/springboot-vue3/src/main/java/com/example/springboot/component/WebSocketServer.java b/springboot-vue3/src/main/java/com/example/springboot/component/WebSocketServer.java index 18785c1..8749b5e 100644 --- a/springboot-vue3/src/main/java/com/example/springboot/component/WebSocketServer.java +++ b/springboot-vue3/src/main/java/com/example/springboot/component/WebSocketServer.java @@ -1,7 +1,11 @@ package com.example.springboot.component; +import java.util.ArrayList; +import java.util.List; import java.util.Map; import java.util.concurrent.ConcurrentHashMap; + +import org.apache.catalina.core.ApplicationContext; import org.slf4j.Logger; import org.slf4j.LoggerFactory; @@ -14,8 +18,8 @@ import javax.websocket.server.PathParam; import javax.websocket.server.ServerEndpoint; +import org.springframework.context.ConfigurableApplicationContext; import org.springframework.stereotype.Component; - import cn.hutool.json.JSONObject; import cn.hutool.json.JSONUtil; @@ -23,16 +27,30 @@ @ServerEndpoint(value = "/api/talk/{username}") @Component public class WebSocketServer { - - private static final Logger log = LoggerFactory.getLogger(WebSocketServer.class); + // @Autowired + // HomeMapper homeMapper; + + static ConfigurableApplicationContext applicationContext; + + //瑙e喅鏃犳硶娉ㄥ叆mapper闂 //浣跨敤鏂规硶 homeMapper=WebSocketServer.applicationContext.getBean(HomeMapper.class); + public static void setApplicationContext(ConfigurableApplicationContext configurableApplicationContext) { + WebSocketServer.applicationContext = configurableApplicationContext; + } + + + private static final Logger log = LoggerFactory.getLogger(WebSocketServer.class); + private List<String> messages; /** * 璁板綍褰撳墠鍦ㄧ嚎杩炴帴鏁� */ public static final Map<String, WebSocketServer> sessionMap = new ConcurrentHashMap<>(); - private String username; - private Session session; + String username; + Session session; + public WebSocketServer() { + this.messages = new ArrayList<>(); + } /** * 杩炴帴寤虹珛鎴愬姛璋冪敤鐨勬柟娉� */ @@ -75,12 +93,13 @@ public void onMessage(String message, Session session, @PathParam("username") String username) { log.info("鏈嶅姟绔敹鍒扮敤鎴穟sername={}鐨勬秷鎭�:{}", username, message); JSONObject obj = JSONUtil.parseObj(message); - String text = obj.getStr("data"); JSONObject jsonObject = new JSONObject(); - jsonObject.set("message", "ngng"); + jsonObject.set("message", text); + this.messages.add(text); this.sendMessage(jsonObject.toString()); //JSONUtil.toJsonStr(jsonObject) + } @OnError @@ -115,4 +134,12 @@ } } + public List<String> getMessages() { + return messages; + + } + + public void clearMessages() { + messages.clear(); + } } -- Gitblit v1.8.0