<template>
  <div class="app-container">
    <el-form label-width="100px" :inline="true">
      <el-row :gutter="8" >
        <el-col :span="12">
          <el-input v-model="url" type="text" style="width: 100%" />
        </el-col>
        <el-col :span="12">
          <el-button @click="join" type="primary">连接</el-button>
          <el-button @click="exit" type="danger">断开</el-button>
        </el-col>
      </el-row>
      <el-row :gutter="8" class="mt10">
        <el-col :span="24">
          <el-input type="textarea" v-model="message" :rows="5" />
        </el-col>
      </el-row>
      <el-row :gutter="8" class="mt10">
        <el-col :span="24">
          <el-button type="info" @click="send">发送消息</el-button>
        </el-col>
      </el-row>
      <el-row :gutter="8" class="mt20">
        <el-col :span="24">
          <el-input type="textarea" v-model="text_content" :rows="5" />
        </el-col>
      </el-row>
    </el-form>
  </div>
</template>

<script>
export default {
  name: 'WebSocketExample',
  data() {
    return {
      url: "ws://localhost:3334/websocket/message",
      message: "",
      text_content: "",
      ws: null,
    };
  },
  methods: {
    join() {
      const wsuri = this.url;
      this.ws = new WebSocket(wsuri);
      const self = this;
      this.ws.onopen = function (event) {
        self.text_content = self.text_content + "已经打开连接!" + "\n";
      };
      this.ws.onmessage = function (event) {
        self.text_content = event.data + "\n";
      };
      this.ws.onclose = function (event) {
        self.text_content = self.text_content + "已经关闭连接!" + "\n";
      };
      this.ws.onerror = function (event) {
        self.text_content = self.text_content + "连接异常!" + "\n";
      }
    },
    exit() {
      if (this.ws) {
        this.ws.close();
        this.ws = null;
      }
    },
    send() {
      if (this.ws) {
        this.ws.send(this.message);
      } else {
        alert("未连接到服务器");
      }
    },
  },
};
</script>
