WebSocket在Java Spring Boot+Vue框架中实现消息推送功能
以下是一个简化的Java Spring Boot后端代码示例,用于创建WebSocket端点,并在Vue前端接收和显示消息。
Java后端代码:
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;
@Configuration
@EnableWebSocket
public class WebSocketConfig implements WebSocketConfigurer {
@Override
public void registerWebSocketHandlers(WebSocketHandlerRegistry registry) {
registry.addHandler(messageHandler(), "/ws/messages")
.setAllowedOrigins("http://localhost:8080"); // 允许Vue前端的源
}
@Bean
public WebSocketMessageHandler messageHandler() {
return new WebSocketMessageHandler(); // 自定义的WebSocketMessageHandler实现
}
}
Vue前端代码:
<template>
<div>
<div v-for="message in messages" :key="message">{{ message }}</div>
</div>
</template>
<script>
export default {
data() {
return {
messages: [],
socket: null
};
},
created() {
this.connectWebSocket();
},
methods: {
connectWebSocket() {
this.socket = new WebSocket('ws://localhost:8080/ws/messages');
this.socket.onmessage = this.handleMessage;
this.socket.onclose = this.handleClose;
this.socket.onerror = this.handleError;
},
handleMessage(event) {
this.messages.push(event.data);
},
handleClose() {
console.log('WebSocket Closed');
},
handleError(event) {
console.error('WebSocket Error', event);
},
sendMessage(message) {
if (this.socket.readyState === WebSocket.OPEN) {
this.socket.send(message);
}
}
},
beforeDestroy() {
this.socket.close();
}
};
</script>
在这个例子中,我们创建了一个简单的WebSocket连接,在Vue前端显示从后端接收的消息。记得在实际部署时,WebSocket的URL需要根据实际部署的服务器地址进行相应的替换。
评论已关闭