在Spring Boot和Vue 3中集成WebSocket可以实现实时的双向通信,这在许多现代Web应用中都是非常有用的,比如实时聊天、实时数据更新等。以下是一个基本的指南,介绍如何在Spring Boot后端和Vue 3前端之间使用WebSocket。
1 Spring Boot 后端
1.1 添加依赖
在你的Spring Boot项目的pom.xml
文件中添加WebSocket的依赖:
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-websocket</artifactId>
</dependency>
1.2 配置WebSocket
创建一个配置类来启用WebSocket并设置其路径:
import org.springframework.context.annotation.Configuration;
import org.springframework.web.socket.config.annotation.EnableWebSocket;
import org.springframework.web.socket.config.annotation.WebSocketConfigurer;
import org.springframework.web.socket.config.annotation.WebSocketHandlerRegistry;
import your.package.WebSocketHandler; // 替换为你的WebSocketHandler实现类
/**
* WebSocket 配置类
*/
@Configuration
class WebSocketConfig {
@Bean
fun serverEndpointExporter(): ServerEndpointExporter {
return ServerEndpointExporter()
}
}
1.3 实现WebSocketHandler
创建一个类实现WebSocketHandler
接口,处理WebSocket连接、消息接收和发送:
@ServerEndpoint("/WebSocket/{clientId}")
@Component
class WebSocketServer {
private var session: Session? = null
private var clientId: String? = null
class WebSocketResult {
var command: String? = null
var data: Any? = null
var flag: Boolean = true
}
companion object {
private val webSockets = CopyOnWriteArraySet<WebSocketServer>()
fun sendDataPacketDebug(dataPacketDebug: WimDataPacketDebug) {
webSockets.forEach {
it.session?.basicRemote?.sendText(WebSocketResult().apply {
command = "dataPacketDebug"
data = dataPacketDebug
flag = true
}.toJSONString())
}
}
}
/**
* 发送心跳包
*/
@Scheduled(fixedRate = 5000)
fun sendHearBeat() {
// println("heart beat")
webSockets.forEach {
it.session?.basicRemote?.sendText(WebSocketResult().apply {
command = "heartBeat"
data = null
flag = true
}.toJSONString())
}
}
@OnOpen
fun onOpen(session: Session, @PathParam("clientId") clientId: String){
this.session = session
this.clientId = clientId
webSockets.add(this)
println("websocket opened! $clientId")
}
@OnClose
fun onClose() {
println("websocket closed! $clientId")
webSockets.remove(this)
}
@OnMessage
fun onMessage(message: String, session: Session) {
println(session.id)
println(message)
// session.basicRemote.sendText("wenqiang")
}
@OnError
fun onError(session: Session, error: Throwable) {
println(error.message)
}
}
2 Vue3 前端
2.1 安装依赖
如果你还没有安装
sockjs-client
或@stomp/stompjs
(如果你打算使用STOMP协议的话),你可能需要安装它们。不过,对于简单的WebSocket通信,只需要浏览器内置的WebSocket API即可。
2.2 建立WebSocket连接
在你的Vue组件中,你可以使用WebSocket API来建立连接并处理消息:
<script setup>
import { ref, onMounted, onUnmounted } from 'vue';
const socket = ref(null);
const messages = ref([]);
onMounted(() => {
socket.value = new WebSocket('ws://localhost:8080/ws'); // 替换为你的WebSocket服务器地址
socket.value.onopen = () => {
console.log('WebSocket connected');
};
socket.value.onmessage = (event) => {
const message = event.data;
messages.value.push(message);
};
socket.value.onclose = () => {
console.log('WebSocket disconnected');
};
socket.value.onerror = (error) => {
console.error('WebSocket error:', error);
};
});
onUnmounted(() => {
if (socket.value) {
socket.value.close();
}
});
const sendMessage = (message) => {
if (socket.value && socket.value.readyState === WebSocket.OPEN) {
socket.value.send(message);
}
};
</script>
<template>
<div>
<ul>
<li v-for="message in messages" :key="message">{{ message }}</li>
</ul>
<input type="text" @keyup.enter="sendMessage($event.target.value)" />
</div>
</template>
在这个例子中,我们创建了一个简单的Vue3组件,它建立了一个WebSocket连接,并在接收到消息时将其添加到messages
数组中。用户可以通过输入框发送消息到WebSocket服务器。
确保你的Spring Boot应用正在运行,并且WebSocket服务器地址与Vue客户端中使用的地址相匹配。这样,你就可以在Spring Boot和Vue 3之间实现实时的WebSocket通信了。