vue+SpringBoot使用WebSocket方式
作者:遇见很ok
WebSocket是一种全双工通信协议,通过HTTP升级机制建立连接,支持实时双向数据传输,示例代码展示了如何在Java Spring Boot和Vue.js中实现WebSocket服务和客户端
WebSocket 原理
WebSocket 是一种网络通信协议,旨在通过单一的、持久的连接,在客户端和服务端之间进行双向数据交换。
它的工作原理如下:
- 协议握手:WebSocket 协议是基于 HTTP 协议的,客户端首先通过 HTTP 请求向服务器发送一个 WebSocket 握手请求(HTTP 协议的 Upgrade 请求),服务器如果支持 WebSocket,就会返回一个 101 响应,表示协议已切换到 WebSocket。
- 连接建立:一旦握手完成,客户端和服务器就会建立起一个全双工(双向)通信连接,客户端和服务器可以随时相互发送数据,而无需重新建立连接。
- 数据传输:WebSocket 允许客户端和服务器在任意时刻发送消息,数据传输是基于帧的(每个数据包都是一个帧),并且帧的数据格式是二进制或文本。
- 连接关闭:当通信结束时,任一方都可以发起连接关闭请求,关闭 WebSocket 连接。
与传统的 HTTP 请求-响应模式不同,WebSocket 提供了低延迟、实时、双向通信的优势,特别适用于需要即时数据传输的应用,如即时聊天、在线游戏、股票行情等。
示例代码
1. Java 服务端(使用 Spring Boot + WebSocket)
在 Java 服务端,我们可以使用 Spring Boot 和 Spring WebSocket 来实现 WebSocket 服务。
步骤 1:添加依赖
首先,确保你的 pom.xml
文件中有以下依赖:
<dependencies> <!-- Spring Boot WebSocket 支持 --> <dependency> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-starter-websocket</artifactId> </dependency> <!-- Spring Boot Web 相关支持 --> <dependency> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-starter-web</artifactId> </dependency> </dependencies>
步骤 2:创建 WebSocket 配置类
import org.springframework.context.annotation.Configuration; import org.springframework.messaging.simp.config.MessageBrokerRegistry; import org.springframework.web.socket.config.annotation.EnableWebSocket; import org.springframework.web.socket.config.annotation.WebSocketMessageBrokerConfigurer; import org.springframework.web.socket.config.annotation.StompEndpointRegistry; @Configuration @EnableWebSocket public class WebSocketConfig implements WebSocketMessageBrokerConfigurer { @Override public void configureMessageBroker(MessageBrokerRegistry config) { // 设定应用程序前缀(消息传递的目的地) config.enableSimpleBroker("/topic"); // 设置消息发送的目标前缀 config.setApplicationDestinationPrefixes("/app"); } @Override public void registerStompEndpoints(StompEndpointRegistry registry) { // 设定WebSocket端点 registry.addEndpoint("/ws").withSockJS(); } }
步骤 3:创建消息处理器
import org.springframework.messaging.handler.annotation.MessageMapping; import org.springframework.messaging.simp.SimpMessagingTemplate; import org.springframework.stereotype.Controller; @Controller public class WebSocketController { private final SimpMessagingTemplate messagingTemplate; public WebSocketController(SimpMessagingTemplate messagingTemplate) { this.messagingTemplate = messagingTemplate; } @MessageMapping("/chat") public void sendMessage(String message) { // 发送消息到 /topic/chat messagingTemplate.convertAndSend("/topic/chat", message); } }
messagingTemplate.convertAndSend("/topic/chat", message); } }
步骤 4:启动 Spring Boot 应用
创建一个启动类并运行应用:
import org.springframework.boot.SpringApplication; import org.springframework.boot.autoconfigure.SpringBootApplication; @SpringBootApplication public class WebSocketApplication { public static void main(String[] args) { SpringApplication.run(WebSocketApplication.class, args); } }
2. Vue 客户端(使用 Vue + WebSocket)
在 Vue 客户端中,我们可以使用原生的 WebSocket API 或者使用库(如 sockjs-client
)来简化处理。
步骤 1:安装依赖
在 Vue 项目中,我们首先安装 sockjs-client
和 stompjs
库:
npm install sockjs-client stompjs --save
步骤 2:创建 WebSocket 服务
创建一个 Vue 文件,使用 WebSocket 来连接到后端:
import SockJS from 'sockjs-client'; import Stomp from 'stompjs'; export default { data() { return { stompClient: null, message: '' }; }, mounted() { this.connect(); }, methods: { connect() { const socket = new SockJS('http://localhost:8080/ws'); this.stompClient = Stomp.over(socket); this.stompClient.connect({}, frame => { console.log('Connected: ' + frame); // 订阅消息 this.stompClient.subscribe('/topic/chat', (messageOutput) => { this.message = messageOutput.body; }); }); }, sendMessage() { this.stompClient.send("/app/chat", {}, "Hello, WebSocket!"); } } };
步骤 3:展示消息
在模板中展示接收到的消息,并提供一个按钮来发送消息:
<template> <div> <div> <h2>Received Message: {{ message }}</h2> </div> <button @click="sendMessage">Send Message</button> </div> </template> <script> export default { data() { return { message: '' }; }, methods: { sendMessage() { this.$emit('sendMessage', 'Hello Server'); } } } </script>
步骤 4:运行客户端
确保你的 Vue 应用能够与后端服务通信,启动 Vue 应用并检查浏览器控制台的输出。
总结
- WebSocket 原理:WebSocket 是一种全双工协议,建立连接后,客户端和服务器之间可以实时、双向地交换数据。它基于 HTTP 协议的升级机制,通过一个握手过程,客户端与服务器建立 WebSocket 连接,并且后续通信无需重新建立连接。
- Java 服务端:Spring Boot 提供了对 WebSocket 的内建支持,我们通过
@MessageMapping
注解来处理客户端发送的消息,使用SimpMessagingTemplate
来推送消息到订阅的客户端。 - Vue 客户端:Vue 客户端使用
SockJS
和Stomp.js
来实现 WebSocket 连接,并能够接收服务器推送的消息。用户可以通过按钮发送消息,服务器接收到消息后进行广播。
以上为个人经验,希望能给大家一个参考,也希望大家多多支持脚本之家。