websocket vue操作

let websocket: WebSocket;
/** websocket测试 */
function connectWebsocket() {
  if (typeof WebSocket === "undefined") {
    console.log("您的浏览器不支持WebSocket");
    return;
  }

  // let ip = window.location.hostname + ":8080";
  let ip = "10.192.30.161:8080";
  let url = `ws://${ip}/websocket/download`;
  // 打开一个websocket
  websocket = new WebSocket(url);

  // 建立连接
  websocket.onopen = () => {
    console.log("websocket已连接");
    // websocket.send("ping");
  };
  // 客户端接收服务端返回的数据
  websocket.onmessage = (evt) => {
    let data = evt.data
    console.log("websocket返回的数据:", data);
    if (data.length > 0) {
      handleSearch();
    }
  };
  // 发生错误时
  websocket.onerror = (evt) => {
    console.log("websocket错误:", evt);
  };
  // 关闭连接
  websocket.onclose = (evt) => {
    console.log("websocket关闭:", evt);
  };
}
connectWebsocket();

// 监听窗口关闭事件,当窗口关闭时,主动去关闭websocket连接,防止连接还没断开就关闭窗口,server端会抛异常。
window.onbeforeunload = function () {
  websocket.close();
}

你可能感兴趣的:(websocket)