欢迎来到尧图网

客户服务 关于我们

您的位置:首页 > 科技 > 能源 > Spring Boot向Vue发送消息通过WebSocket实现通信

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

2025/4/7 23:53:51 来源:https://blog.csdn.net/qq_62408075/article/details/146921316  浏览:    关键词: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协议及其端口

版权声明:

本网仅为发布的内容提供存储空间,不对发表、转载的内容提供任何形式的保证。凡本网注明“来源:XXX网络”的作品,均转载自其它媒体,著作权归作者所有,商业转载请联系作者获得授权,非商业转载请注明出处。

我们尊重并感谢每一位作者,均已注明文章来源和作者。如因作品内容、版权或其它问题,请及时与我们联系,联系邮箱:809451989@qq.com,投稿邮箱:809451989@qq.com

热搜词