zoukankan      html  css  js  c++  java
  • websocket推送进度条百分比给前台

    说明:后台springboot项目 前台vue+element-UI

    直接放代码:

    //别忘了开启springboot的websocket
    <dependency>
       <groupId>org.springframework.boot</groupId>
       <artifactId>spring-boot-starter-websocket</artifactId>
    </dependency>
    //后台代码
    首先在启动类中注入
    @Bean
    public ServerEndpointExporter serverEndpointExporter() {
       return new ServerEndpointExporter();
    }

    @Component
    @ServerEndpoint("/websocket")
    public class WebSocket {

      private Session session;

      private static CopyOnWriteArraySet<WebSocket> webSockets = new CopyOnWriteArraySet<>();
      private String msg = "0";

      @OnOpen
      public void onOpen(Session session) {
        this.session = session;
        webSockets.add(this);
        sendAllMessage(msg);
      }

      /**
      * 关闭调用方法
      */
      @OnClose
      public void onClose() {
        webSockets.remove(this);
      }

      @OnMessage
      public void onMessage(String msg) {
      }

      /**
      * 消息广播到前台
      *
      * @param msg
      */
      public void sendAllMessage(String msg) {
        for (WebSocket webSocket : webSockets) {
          try {
            webSocket.session.getBasicRemote().sendText(msg);
            } catch (Exception e) {
            e.printStackTrace();
          }
        }
      }

    }

    //前台vue
    <div style="margin-top: 20px;">
        <el-progress :percentage="percentMsg"></el-progress>
    </div>


    //前台js mounted是vue用来初始化的 methods里定义的是方法
     mounted() {
        // WebSocket
        if ("WebSocket" in window) {
          this.websocket = new WebSocket("ws://localhost:8080/websocket");
          this.initWebSocket();
        } else {
          alert("当前浏览器 Not support websocket");
        }
      },

      methods: {
        initWebSocket() {
          // 连接错误
          this.websocket.onerror = this.setErrorMessage;

          // 连接成功
          this.websocket.onopen = this.setOnopenMessage;

          // 收到消息的回调
          this.websocket.onmessage = this.setOnmessageMessage;

          // 连接关闭的回调
          this.websocket.onclose = this.setOncloseMessage;

          // 监听窗口关闭事件,当窗口关闭时,主动去关闭websocket连接,防止连接还没断开就关闭窗口,server端会抛异常。
          window.onbeforeunload = this.onbeforeunload;
        },
        setErrorMessage() {
          // console.log(
          //   "WebSocket连接发生错误   状态码:" + this.websocket.readyState
          // );
        },
        setOnopenMessage() {
          // console.log("WebSocket连接成功    状态码:" + this.websocket.readyState);
        },
        setOnmessageMessage(event) {
          // 服务器推送的消息
          console.log("服务端返回:" + event.data);
          //percentMsg就是绑定的进度值
          this.percentMsg = parseInt(event.data);
          if (this.percentMsg == 100) {
         //如果进度是100 dialog框就隐藏
            this.dialogPortVisible = false;
          }
        },
        setOncloseMessage() {
          // console.log("WebSocket连接关闭    状态码:" + this.websocket.readyState);
        },
        onbeforeunload() {
          this.closeWebSocket();
        },
        closeWebSocket() {
          this.websocket.close();
        },
       //format函数是和进度条组件绑定的 具体可查看element-ui组件官网进度条
       format(percentage){
        return percentage === 100 ? "满" : `${percentage}%`
       }
     }
    //后台调用推送数据

    @RestController
    public class ExportTxt {

      @Autowired
      private WebSocket websocket;

      @RequestMapping(value = "/test", method = RequestMethod.POST, produces = "application/json;charset=utf-8")
      public void test(){
        String msg = "";
        int a = 0;
        for(int i=0;i<5;i++){
          msg = String.valueOf(a);
          websocket.sendAllMessage(msg);
          a=a+20;
        }
      }
    }

    进度条进度数据 效果如下

  • 相关阅读:
    年轻人的第一个 Spring Boot 应用,太爽了!
    面试问我 Java 逃逸分析,瞬间被秒杀了。。
    Spring Boot 配置文件 bootstrap vs application 到底有什么区别?
    坑爹的 Java 可变参数,把我整得够惨。。
    6月来了,Java还是第一!
    Eclipse 最常用的 10 组快捷键,个个牛逼!
    Spring Cloud Eureka 自我保护机制实战分析
    今天是 Java 诞生日,Java 24 岁了!
    厉害了,Dubbo 正式毕业!
    Spring Boot 2.1.5 正式发布,1.5.x 即将结束使命!
  • 原文地址:https://www.cnblogs.com/xuchao0506/p/12638521.html
Copyright © 2011-2022 走看看