<template>

  <div style="width: 300px;margin: 0 auto;padding:30px">
    <el-input v-model="text" label="文本框" ></el-input>
    <div style="height: 30px"></div>
    <el-button @click="mySendMsg()">发送信息</el-button>
  </div>
</template>

<script>
  export default {
    name: "webSocket",
    components: {},
    data() {
      return {
        websock: null,
        text: '',
      }
    },
    computed: {},
    created() {
      this.initWebSocket();
    },
    mounted() {
      //this.initWebSocket();
    },
    destroyed: function () { // 离开页面生命周期函数
      this.websocketOnclose();
    },
    methods: {

      mySendMsg() {
        this.websocketSend(this.text)
      },

      initWebSocket: function () {
        // WebSocket与普通的请求所用协议有所不同，ws等同于http，wss等同于https
        console.log("调用了链接 websock")
        var userId = "1";
        //var url = "ws://localhost:9696/webSocket/" + userId;
        var url = "ws://localhost:8080/websocket/message"
        console.log(url);
        this.websock = new WebSocket(url);
        this.websock.onopen = this.websocketOnopen;
        this.websock.onerror = this.websocketOnerror;
        this.websock.onmessage = this.websocketOnmessage;
        this.websock.onclose = this.websocketOnclose;
      },
      websocketOnopen: function () {
        console.log("WebSocket连接成功");
        //心跳检测重置
        //this.heartCheck.reset().start();
      },
      websocketOnerror: function (e) {
        console.log("WebSocket连接发生错误");
        this.reconnect();
      },
      websocketOnmessage: function (e) {
        console.log('监听关闭' + e)
        console.log("-----接收消息-------", e.data);
        var data = eval("(" + e.data + ")"); //解析对象
      },
      websocketOnclose: function (e) {
        console.log("connection closed (" + e.code + ")");
        this.reconnect();
      },
      websocketSend(text) { // 数据发送
        try {
          this.websock.send(text);
        } catch (err) {
          console.log("send failed (" + err.code + ")");
        }
      },

      reconnect() {
        var that = this;
        if (that.lockReconnect) return;
        that.lockReconnect = true;
        //没连接上会一直重连，设置延迟避免请求过多
        setTimeout(function () {
          console.info("尝试重连...");
          that.initWebSocket();
          that.lockReconnect = false;
        }, 5000);
      },
    }
  }
</script>


<style scoped>

</style>
