websocket实现进度条

评论: 0 浏览: 1244 ***新更新时间: 4周前

websocket实现进度条

一个简易的websocket实现进度条的练习,效果如下:

websocket实现进度条

前端vue3

    
    获取进度


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.data
        if(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');
      }
    },
  }
}

后端java

  1. pom.xml引入websocket
     org.springframework
     spring-websocket
     5.3.19
 
  1. 先配置一个websocket的配置类。
@Configuration
@EnableWebSocket
public class WebSocketConfig implements WebSocketConfigurer {
    @Override
    public void registerWebSocketHandlers(WebSocketHandlerRegistry registry) {
        registry.addHandler(webSocketHandler(), "/ws")
        //这里的url一定要和前端的对应上
                .setAllowedOrigins("*"); // 允许跨域
    }
    @Bean
    public WebSocketHandler webSocketHandler() {
        return new WebSocketHandler();
    }
}
  1. 实现websocket的操作方法。
public class WebSocketHandler extends TextWebSocketHandler {
    @Override
    public void handleTextMessage(WebSocketSession session, TextMessage message) throws IOException {
        // 处理接收到的消息
        System.out.println("Received message: " + message.getPayload());
        int progress = 0;
        for (int i = 0; i 
                
                
                

发表评论:

◎欢迎参与讨论,请在这里发表您的看法、交流您的观点。

点击启动AI问答
Draggable Icon