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中发送消息

相关推荐
王王碎冰冰4 小时前
基于 Vue3@3.5+跟Ant Design of Vue 的二次封装的 Form跟搜索Table
前端·vue.js
天蓝色的鱼鱼5 小时前
Element UI 2.X 主题定制完整指南:解决官方工具失效的实战方案
前端·vue.js
我是日安6 小时前
从零到一打造 Vue3 响应式系统 Day 8 - Effect:深入剖析嵌套 effect
前端·vue.js
DevUI团队6 小时前
🚀 MateChat V1.8.0 震撼发布!对话卡片可视化升级,对话体验全面进化~
前端·vue.js·人工智能
好好好明天会更好6 小时前
pinia从定义到运用
前端·vue.js
代码小学僧6 小时前
Vite 项目最简单方法解决部署后 Failed to fetch dynamically imported Error问题
前端·vue.js·vite
后端小张7 小时前
基于飞算AI的图书管理系统设计与实现
spring boot
东坡白菜7 小时前
SSE 实现 AI 对话中的流式输出
javascript·vue.js
猩兵哥哥11 小时前
前端面向对象设计原则运用 - 策略模式
前端·javascript·vue.js
EMT12 小时前
在 Vue 项目中使用 URL Query 保存和恢复搜索条件
javascript·vue.js