zoukankan      html  css  js  c++  java
  • Vue websocket编程

    <template>
      <div class="dashboard-container">
        <el-row type="flex" justify="space-between">
          <el-col :span="8">
            <el-input v-model="sendMessage"></el-input><el-button plain @click="send">发送</el-button>
          </el-col>
        </el-row>
        <el-input type="textarea" :rows="2" placeholder="请输入内容" v-model="txtMessage"></el-input>
      </div>
    </template>
    
    <script>
    
    export default {
      name: 'chat',
      data() {
        return {
          sendMessage: '',
          txtMessage: '',
          path: 'ws://10.211.55.3:6690/Echo',
          socket: ''
        }
      },
      mounted() {
        // 初始化
        this.init()
      },
      created() {
      },
      methods: {
        init: function() {
          if (typeof (WebSocket) === 'undefined') {
            alert('您的浏览器不支持socket')
          } else {
            // 实例化socket
            this.socket = new WebSocket(this.path)
            // 监听socket连接
            this.socket.onopen = this.open
            // 监听socket错误信息
            this.socket.onerror = this.error
            // 监听socket消息
            this.socket.onmessage = this.getMessage
          }
        },
        open: function() {
          console.log('socket连接成功')
        },
        error: function() {
          console.log('连接错误')
        },
        getMessage: function(msg) {
          this.txtMessage = msg.data
          console.log(msg.data)
        },
        send: function() {
          this.socket.send(this.sendMessage)
        },
        close: function() {
          console.log('socket已经关闭')
        }
      },
      destroyed() {
        // 销毁监听
        this.socket.onclose = this.close
      }
    }
    </script>
    
    <style rel="stylesheet/scss" lang="scss" scoped>
    .dashboard-container {
      padding-top: 1px;
      padding-left: 10px;
      background-color: rgb(240, 242, 245);
      // .chart-wrapper {
      //   background: #fff;
      //   padding: 16px 16px 0;
      //   margin-bottom: 32px;
      // }
    }
    </style>
  • 相关阅读:
    JS数组去重
    正则表达式验证邮箱手机号等
    js中的事件委托
    c++刷题(6/100)最长上升子序列
    c++刷题(3/100)数独,栈和队列
    在express中HMR(合并express和webpack-dev-server)
    面试整理(3)js事件委托
    面试整理(2)跨域:jsonp与CORS
    面试整理(1):原生ajax
    styled-components真的好吗?
  • 原文地址:https://www.cnblogs.com/hwubin5/p/11111657.html
Copyright © 2011-2022 走看看