<template>
  <div>
    <img ref="imagePlayer" alt="实时图像" width="100%" height="100%"/>
  </div>
</template>

<script>
export default {
  data() {
    return {
      imagePlayer: null,
      socket: null,
      device_id: localStorage.getItem("realvp_device_id"),
      tokenData: {
        token: localStorage.getItem("token"),
        ip: localStorage.getItem("ip"),
        userId: localStorage.getItem("userId"),
        username: localStorage.getItem("username"),
        to_user_id: this.to_user_id,
      },
    };
  },
  mounted() {
    this.imagePlayer = this.$refs.imagePlayer;
    this.initWebSocket();
  },
  methods: {
    initWebSocket() {
      let socketUrl =
        "wss://gep.ljsea.top/device/get_real_time_image?device_id=" +   //wss://gep.ljsea.top/device/get_real_time_image?device_id=     wss://vps.ljsea.top/tool/video_real_time?device_id=
        this.device_id +
        "&token=" +
        this.tokenData.token;
      this.socket = new WebSocket(socketUrl);
      this.socket.onopen = () => {
        console.log('WebSocket连接成功');
      };
      this.socket.onmessage = (event) => {
        const blob = new Blob([event.data], { type: 'image/jpeg' });
        const objectURL = URL.createObjectURL(blob);
        this.imagePlayer.src = objectURL;
      };
      this.socket.onclose = () => {
        console.log('WebSocket连接关闭');
        this.imagePlayer.src = "";
      };
      this.socket.onerror = (error) => {
        console.error('WebSocket出现错误:', error);
      };
    },
  },
  beforeUnmount() {
    if (this.socket) {
        this.socket.onmessage = null;
        console.log('关闭WebSocket连接');
      this.socket.close();
       window.location.reload();
    }
  },
};
</script>

<style scoped>
img {
  width: 100%;
  margin: 0 auto;
}
</style>