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;
    }
  }
}

進度條進度數據 效果如下

 


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM