websocket实现进度条
做一个简易的websocket实现进度条的练习,效果如下:
前端vue3
<template><el-progress type="circle" :percentage="this.progressValue" :status="this.perstatus" /><el-button @click="sendMessage()">获取进度</el-button>
</template><script>
import { ref } from 'vue';
const progressValue = ref(0);
const perstatus = ref('');
const socket = new WebSocket('ws://url/ws');export default {name: 'App',components: {},mounted(){this.connect();},unmounted(){this.beforeDestroy();},data(){return {progressValue,perstatus};},methods:{connect() {socket.onopen = function() {console.log('WebSocket connected');};socket.onmessage = function(event) {console.log('Received message: ', event.data);progressValue.value= +event.dataif(progressValue.value>=100){perstatus.value='success'}console.log(progressValue.value+"---"+perstatus.value);};socket.onerror = function(event) {console.error('WebSocket error observed:', event);};},beforeDestroy() {if (socket) {socket.close();console.log('close socket connect');}},sendMessage() {if (socket.readyState === WebSocket.OPEN) {socket.send('get progress');}},}
}
</script>
后端java
- pom.xml引入websocket
<dependency><groupId>org.springframework</groupId><artifactId>spring-websocket</artifactId><version>5.3.19</version></dependency>
- 先配置一个websocket的配置类。
@Configuration
@EnableWebSocket
public class WebSocketConfig implements WebSocketConfigurer {@Overridepublic void registerWebSocketHandlers(WebSocketHandlerRegistry registry) {registry.addHandler(webSocketHandler(), "/ws")//这里的url一定要和前端的对应上.setAllowedOrigins("*"); // 允许跨域}@Beanpublic WebSocketHandler webSocketHandler() {return new WebSocketHandler();}
}
- 实现websocket的操作方法。
public class WebSocketHandler extends TextWebSocketHandler {@Overridepublic void handleTextMessage(WebSocketSession session, TextMessage message) throws IOException {// 处理接收到的消息System.out.println("Received message: " + message.getPayload());int progress = 0;for (int i = 0; i < 10; i++) {try {Thread.sleep(500);progress=progress+10;// 发送消息回客户端session.sendMessage(new TextMessage(progress+""));} catch (InterruptedException e) {e.printStackTrace();}}}
}