Spring Boot向Vue發送消息通過WebSocket實現通信

注意:如果后端有contextPath,如/app,那么前端訪問的url就是ip:port/app/ws

后端實現步驟

  • 添加Spring Boot WebSocket依賴
  • 配置WebSocket端點和消息代理
  • 創建控制器,使用SimpMessagingTemplate發送消息

前端實現步驟

  • 安裝sockjs-client和stompjs庫
  • 封裝WebSocket連接工具類
  • 在Vue組件中建立連接,訂閱主題

詳細實現步驟

后端(Spring Boot)實現步驟

1. 添加依賴
<!-- pom.xml -->
<dependency><groupId>org.springframework.boot</groupId><artifactId>spring-boot-starter-websocket</artifactId>
</dependency>
2. 配置WebSocket
@Configuration
@EnableWebSocketMessageBroker
public class WebSocketConfig implements WebSocketMessageBrokerConfigurer {@Overridepublic void registerStompEndpoints(StompEndpointRegistry registry) {// 注冊WebSocket端點,前端連接此地址registry.addEndpoint("/ws").setAllowedOriginPatterns("*") // 解決跨域問題.withSockJS(); // 支持SockJS}@Overridepublic void configureMessageBroker(MessageBrokerRegistry registry) {// 客戶端訂閱的主題前綴registry.enableSimpleBroker("/topic");}
}

3. 發送消息的Controller
@RestController
public class MessageController {@Autowiredprivate SimpMessagingTemplate messagingTemplate;// 發送消息到所有客戶端@GetMapping("/send")public void sendToAll(String message) {messagingTemplate.convertAndSend("/topic/messages", message);}}

前端(Vue)實現步驟

1. 安裝依賴
npm install sockjs-client stompjs
2. 封裝WebSocket工具類
// src/utils/websocket.js
import SockJS from 'sockjs-client';
import Stomp from 'stompjs';
let stompClient = null;
export function connect(url,callback) {const socket = new SockJS(url);stompClient = Stomp.over(socket);stompClient.connect({}, () => {stompClient.subscribe('/topic/messages', (message) => {callback(message.body)});});
}
export function disconnect() {if (stompClient) {stompClient.disconnect();}
}
3. Vue組件集成
<template><div><div>收到消息: {{ receivedMsg }}</div></div>
</template>
<script>
import { connect, disconnect } from '@/ws/websocket';export default {data() {return {inputMsg: '',receivedMsg: ''};},mounted() {connect('http://localhost:8088/ws',(msg)=>{this.receivedMsg = msg;});},beforeDestroy() {disconnect();},methods: {}
};
</script>

測試

向指定客戶端發送消息

后端

        <dependency><groupId>org.springframework.boot</groupId><artifactId>spring-boot-starter-web</artifactId></dependency><dependency><groupId>org.springframework.boot</groupId><artifactId>spring-boot-starter-websocket</artifactId></dependency>
package com.config;import org.springframework.context.annotation.Configuration;
import org.springframework.messaging.simp.config.MessageBrokerRegistry;
import org.springframework.web.socket.config.annotation.EnableWebSocketMessageBroker;
import org.springframework.web.socket.config.annotation.StompEndpointRegistry;
import org.springframework.web.socket.config.annotation.WebSocketMessageBrokerConfigurer;/*** @author cyz*/
@Configuration
@EnableWebSocketMessageBroker
public class WebSocketConfig implements WebSocketMessageBrokerConfigurer {@Overridepublic void registerStompEndpoints(StompEndpointRegistry registry) {// 客戶端連接的端點(WebSocket URL)registry.addEndpoint("/ws")// 允許所有來源(根據需求調整).setAllowedOrigins("*")// 支持 SockJS 降級(兼容不支持 WebSocket 的瀏覽器).withSockJS();}@Overridepublic void configureMessageBroker(MessageBrokerRegistry registry) {// 客戶端訂閱的地址前綴(STOMP 主題)registry.enableSimpleBroker("/portCheckProgress");}
}
package com;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.messaging.simp.SimpMessagingTemplate;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;
/*** @author cyz* @since 2025/4/1 下午5:15*/
@RestController
public class MessageController {@Autowiredprivate SimpMessagingTemplate messagingTemplate;@GetMapping("/send-to-user")public void sendToUser(@RequestParam String userCode, @RequestParam String message) {String destination =  "/portCheckProgress/info/"+userCode;messagingTemplate.convertAndSend(destination, message);}
}
package com;import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;/*** @author cyz* @since 2025/4/1 下午5:12*/
@SpringBootApplication
public class Application {public static void main(String[] args) {SpringApplication.run(Application.class, args);}
}

前端?

// src/utils/websocket.js
import SockJS from 'sockjs-client';
import Stomp from 'stompjs';
let stompClient = null;
export function connect(url,userCode,callback) {const socket = new SockJS(url);stompClient = Stomp.over(socket);stompClient.connect({}, () => {stompClient.subscribe('/portCheckProgress/info/'+userCode, (message) => {callback(message.body)});});
}
export function disconnect() {if (stompClient) {stompClient.disconnect();}
}
<template><div><div>收到消息: {{ receivedMsg }}</div></div>
</template>
<script>
import { connect, disconnect } from '@/ws/websocket';export default {data() {return {inputMsg: '',receivedMsg: ''};},mounted() {var split = location.href.split("?userCode=");var userCode = split[1]connect('http://localhost:8088/ws',userCode,(msg)=>{this.receivedMsg = msg;});},beforeDestroy() {disconnect();},methods: {}
};
</script>

測試

向2中發送消息?

?向3中發送消息?

后端是https?

可以在后端多啟動一個端口,然后重定向到https端口即可,如下

package com.config;import org.apache.catalina.connector.Connector;
import org.springframework.boot.web.embedded.tomcat.TomcatServletWebServerFactory;
import org.springframework.boot.web.servlet.server.ServletWebServerFactory;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;/*** @author cyz*/
@Configuration
public class HttpAndHttpsConfig {@Beanpublic ServletWebServerFactory servletContainer() {TomcatServletWebServerFactory tomcat = new TomcatServletWebServerFactory();tomcat.addAdditionalTomcatConnectors(createHttpConnector());return tomcat;}private Connector createHttpConnector() {Connector connector = new Connector("org.apache.coyote.http11.Http11NioProtocol");connector.setScheme("http");connector.setSecure(false);// 與HTTPS端口一致connector.setPort(8087);// 重定向到HTTPS端口connector.setRedirectPort(8088); return connector;}
}

前端寫的是http協議及其端口

本文來自互聯網用戶投稿,該文觀點僅代表作者本人,不代表本站立場。本站僅提供信息存儲空間服務,不擁有所有權,不承擔相關法律責任。
如若轉載,請注明出處:http://www.pswp.cn/bicheng/75678.shtml
繁體地址,請注明出處:http://hk.pswp.cn/bicheng/75678.shtml
英文地址,請注明出處:http://en.pswp.cn/bicheng/75678.shtml

如若內容造成侵權/違法違規/事實不符,請聯系多彩編程網進行投訴反饋email:809451989@qq.com,一經查實,立即刪除!

相關文章

【嵌入式學習5】PyQt5模塊介紹、創建第一個窗口

目錄 1、PyQt介紹 ①特點 ②主要組件 2、創建第一個窗口 exce_() 1、PyQt介紹 PyQt 是一個用于創建圖形用戶界面&#xff08;GUI&#xff09;應用程序的 Python 庫&#xff0c;它是 Qt 框架的 Python 綁定。 ①特點 跨平臺&#xff1a;支持多種操作系統&#xff0c;包括…

封裝自己的api簽名sdk

api平臺接口調用&#xff0c;需要通過簽名去核對是不是有效的用戶&#xff0c;&#xff0c;一般會給兩個key&#xff0c;acceeKey 和 secretKey,第一個相當于用戶名&#xff0c;第二個相當于密鑰&#xff0c;&#xff0c;&#xff0c;前端通過一定的算法&#xff0c;&#xff0…

很簡單 的 將字幕生成視頻的 方法

一、一鍵將字幕生成視頻的 方法 1、下載任性動圖 10.7 以上版本 2、設置背景 1&#xff09;背景大小 拉伸背景到合適大小&#xff0c;或者選擇右側比例 2&#xff09;、直接空背景&#xff0c;設置背景顏色等詳細信息 3&#xff09;、或者 復制或者突然圖片做背景 3、設置文…

Spring 核心技術解析【純干貨版】- XXI:Spring 第三方工具整合模塊 Spring-Context-Suppor 模塊精講

在企業級開發中&#xff0c;我們經常需要與 第三方工具 進行集成&#xff0c;如 郵件發送、任務調度、緩存管理等。Spring 為此提供了 Spring-Context-Support 模塊&#xff0c;它封裝了多個常見的第三方工具庫&#xff0c;使得開發者可以更方便地將它們集成到 Spring 項目中。…

c++柔性數組、友元、類模版

目錄 1、柔性數組&#xff1a; 2、友元函數&#xff1a; 3、靜態成員 注意事項 面試題&#xff1a;c/c static的作用? C語言&#xff1a; C: 為什么可以創建出 objx 4、對象與對象之間的關系 5、類模版 1、柔性數組&#xff1a; #define _CRT_SECURE_NO_WARNINGS #…

主相機綁定小地圖

資源初始化&#xff1a;在類中通過 property 裝飾器定義主相機、小地圖相機、小地圖精靈等資源屬性&#xff0c;便于在編輯器中賦值。在 start 方法里&#xff0c;當確認這些資源存在后&#xff0c;創建渲染紋理并設置其大小&#xff0c;將渲染紋理與小地圖相機關聯&#xff0c…

linux-core分析-柔性數組越界訪問

文章目錄 core的調用棧core分析修改修改原因柔性數組定義代碼修改總結core的調用棧 vocb core 崩潰:core的大小都是573M左右 Program terminated with signal SIGSEGV, Segmentation fault. #0 0x0000007f789af0d0 in strlen () from /lib/libc.so.6[Current thread is 1 (LW…

leetcode 代碼隨想錄 數組-區間和

題目 給定一個整數數組 Array&#xff0c;請計算該數組在每個指定區間內元素的總和。 輸入&#xff1a; 第一行輸入&#xff1a;為整數數組 Array 的長度 n&#xff0c;接下來 n 行&#xff0c;每行一個整數&#xff0c;表示數組的元素。隨后的輸入為需要計算總和的區間&…

部署nerdctl工具

nerdctl 是一個專為Containerd設計的容器管理命令行工具&#xff0c;旨在提供類似 Docker 的用戶體驗&#xff0c;同時支持 Containerd 的高級特性&#xff08;如命名空間、compose等&#xff09;。 1、下載安裝 wget https://github.com/containerd/nerdctl/releases/downlo…

【論文筆記】DeepSeek-R1 技術報告

最強開源LLM&#xff0c;性能和效果都很棒&#xff1b;在數學、代碼這種有標準正確答案的場景&#xff0c;表現尤為突出&#xff1b;一些其他場景的效果&#xff0c;可能不如DeepSeek-V3和Qwen。 Deepseek-R1沒有使用傳統的有監督微調sft方法來優化模型&#xff0c;而使用了大規…

YOLO學習筆記 | 基于YOLOv5的車輛行人重識別算法研究(附matlab代碼)

基于YOLOv5的車輛行人重識別算法研究 ???????????????????????????? 摘要 本文提出了一種基于YOLOv5的車輛行人重識別(ReID)算法,結合目標檢測與特征匹配技術,實現高效的多目標跟蹤與識別。通過引入注意力機制、優化損失函數和輕量化網絡結構…

Buildroot與Yocto介紹比對

Buildroot 和 Yocto 是嵌入式 Linux 領域最常用的兩大系統構建工具&#xff0c;它們在功能定位、使用方法和適用場景上有顯著差異。以下從專業角度對兩者進行對比分析&#xff1a; 一、Buildroot 核心功能與特點 1. 功能定位 輕量級系統構建工具&#xff1a;專注于快速生成精…

VUE3初始化項目安裝

本次就是作為實驗使用&#xff0c;包括安裝過程中遇到的問題&#xff0c;供大家提供參考&#xff0c;話不多說&#xff0c;看過程&#xff1a; 第1步&#xff1a;首先分別安裝node.js和npm&#xff0c;這步網上有很多資料&#xff0c;很簡單&#xff0c;過程省略了&#xff0c…

GO語言學習(17)Gorm的數據庫操作

目錄 &#x1f3c6;前言 1.Gorm的簡介 2.GORM連接數據庫 2.1 配置DSN Mysql&#xff0c;TiDB&#xff0c;MariaDB PostgreSQL SQL Server SQLite 2.2 gorm.Open連接數據庫 3.數據庫連接池的配置 4.使用GORM對數據庫進行操作&#xff08;重點&#xff09; 4.1 創…

【JavaEE】網絡原理詳解

1.????前言~&#x1f973;&#x1f389;&#x1f389;&#x1f389; Hello, Hello~ 親愛的朋友們&#x1f44b;&#x1f44b;&#xff0c;這里是E綿綿呀????。 如果你喜歡這篇文章&#xff0c;請別吝嗇你的點贊????和收藏&#x1f4d6;&#x1f4d6;。如果你對我的…

第十五屆藍橋杯單片機省賽程序設計試題

同時也是積分賽——測量NE555輸出脈沖頻率 第十五屆 藍橋杯 單片機設計與開發項目 省賽1 第二部分 程序設計試題&#xff08;85 分&#xff09; &#xff08;大學組&#xff09; 一 基本要求 1、使用大賽組委會統一提供的四梯單片機競賽實訓平臺&#xff0c;完成本試題程序…

JavaScript智能對話機器人——企業知識庫自動化

引言 內部知識管理常面臨信息分散、查找困難的問題。本文將使用Node.js和虎躍辦公的智能對話API&#xff0c;構建企業級知識問答機器人&#xff0c;支持自然語言查詢和自動學習。 核心技術 自然語言處理&#xff08;NLP&#xff09;意圖識別機器學習模型微調REST API集成 代…

元宇宙浪潮下,前端開發如何“乘風破浪”?

一、元宇宙對前端開發的新要求 元宇宙的興起&#xff0c;為前端開發領域帶來了全新的挑戰與機遇。元宇宙作為一個高度集成、多維互動的虛擬世界&#xff0c;要求前端開發不僅具備傳統網頁開發的能力&#xff0c;還需要掌握虛擬現實&#xff08;VR&#xff09;、增強現實&#…

Spring Boot 3.4.3 基于 Caffeine 實現本地緩存

在現代企業級應用中,緩存是提升系統性能和響應速度的關鍵技術。通過減少數據庫查詢或復雜計算的頻率,緩存可以顯著優化用戶體驗。Spring Boot 3.4.3 提供了強大的緩存抽象支持,而 Caffeine 作為一款高性能的本地緩存庫,因其優異的吞吐量和靈活的配置,成為許多開發者的首選…

QT Quick(C++)跨平臺應用程序項目實戰教程 6 — 彈出框

目錄 1. Popup組件介紹 2. 使用 上一章內容完成了音樂播放器程序的基本界面框架設計。本小節完成一個簡單的功能。單擊該播放器頂部菜單欄的“關于”按鈕&#xff0c;彈出該程序的相關版本信息。我們將使用Qt Quick的Popup組件來實現。 1. Popup組件介紹 Qt 中的 Popup 組件…