美文网首页
websocket基础

websocket基础

作者: Wrestle_Mania | 来源:发表于2021-04-26 10:31 被阅读0次
    <template lang="html">
      <div class="">
        <el-row :gutter="20">
          <el-col :span="8">
            <el-input v-model="input" placeholder="请输入内容"></el-input>
          </el-col>
          <el-col :span="12">
            <el-button type="primary" @click="sendData">发送</el-button>
            <el-button type="success" @click="open">开启</el-button>
            <el-button type="danger" @click="close">关闭</el-button>
          </el-col>
        </el-row>
      </div>
    </template>
    
    <script>
    export default {
      data() {
        return {
          socket: null,
          input: "",
        };
      },
      methods: {
        sendData() {
          this.socket.send(this.input);
        },
        close() {
          this.socket.close();
        },
        open() {
          this.doInit();
        },
        doInit() {
          this.socket = new WebSocket("ws://127.0.0.1:8888");
    
          // WebSocket 连接成功时触发
          this.socket.addEventListener("open", (event) => {
            console.log(event);
          });
    
          // WebSocket 收到数据时触发
          this.socket.addEventListener("message", function (event) {
            console.log(event);
            console.log(event.data);
          });
    
          // WebSocket 连接被关闭时触发
          this.socket.addEventListener("close", function (event) {
            console.log(event);
          });
    
          // WebSocket 连接因错误而关闭时触发
          this.socket.addEventListener("error", function (event) {
            console.log(event);
          });
        },
      },
      created() {
        this.doInit();
      },
    };
    </script>
    

    相关文章

      网友评论

          本文标题:websocket基础

          本文链接:https://www.haomeiwen.com/subject/zqwsrltx.html