当前位置: 首页 > news >正文

Spring Boot向Vue发送消息通过WebSocket实现通信

后端实现步骤

  • 添加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 {

    @Override
    public void registerStompEndpoints(StompEndpointRegistry registry) {
        // 注册WebSocket端点,前端连接此地址
        registry.addEndpoint("/ws")
                .setAllowedOriginPatterns("*") // 解决跨域问题
                .withSockJS(); // 支持SockJS
    }

    @Override
    public void configureMessageBroker(MessageBrokerRegistry registry) {
        // 客户端订阅的主题前缀
        registry.enableSimpleBroker("/topic");
    }
}

3. 发送消息的Controller
@RestController
public class MessageController {

    @Autowired
    private 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 {
    @Override
    public void registerStompEndpoints(StompEndpointRegistry registry) {
        // 客户端连接的端点(WebSocket URL)
        registry.addEndpoint("/ws")
                // 允许所有来源(根据需求调整)
                .setAllowedOrigins("*")
                // 支持 SockJS 降级(兼容不支持 WebSocket 的浏览器)
                .withSockJS();
    }

    @Override
    public 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 {
    @Autowired
    private 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中发送消息 

相关文章:

  • 解决ubuntu18.04无法进入系统桌面
  • 【文献阅读】Vision-Language Models for Vision Tasks: A Survey
  • Spark,HDFS概述
  • Android7 Input(三)EventHub
  • HTTP响应数据包全面解析:结构、原理与最佳实践
  • [GESP202503 C++六级题解]:P1196:环线
  • 基于Vue的低代码可视化表单设计器 FcDesigner 3.2.11更新说明
  • latex下载软件
  • 蓝桥杯准备(前缀和差分)
  • 【矩阵快速幂】P3702 [SDOI2017] 序列计数|省选-
  • C++ 新特性 | C++ 11 | 移动语义
  • 【huggingface 数据下载】ssh / https 不同的下载流程,hf 镜像下载注意事项
  • ⼆、Kafka客户端消息流转流程
  • Ubuntu环境安装
  • 【网安面经合集】42 道高频 Web 安全面试题全解析(附原理+防御+思路)
  • Java基础-25-继承-方法重写-子类构造器的特点-构造器this的调用
  • 基于langchain实现GraphRAG:基于图结构的检索增强生成系统
  • Linux(24)——系统调优
  • MySQL数据库和表的操作之数据库表操作
  • Day3 蓝桥杯省赛冲刺精炼刷题 —— 排序算法与贪心思维
  • 太平人寿党委书记赵峰调任海南省政府党组成员
  • 央媒:安徽凤阳鼓楼坍塌楼宇部分非文物,系违规复建的“假古董”
  • 零跑汽车一季度营收破百亿元:净亏收窄至1.3亿元,毛利率14.9%创新高
  • 新疆巴音郭楞州和硕县发生4.6级地震,震源深度10千米
  • 去年中企海外新增风电装机量5.4GW,亚太区域占比过半
  • 复旦兼职教授高纪凡首秀,勉励学子“看三十年才能看见使命”