Vue websocket编程

Posted hwubin5

tags:

篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了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>

 

以上是关于Vue websocket编程的主要内容,如果未能解决你的问题,请参考以下文章

C++ socket编程 和 MFC socket编程 有啥区别??

C++ socket编程 和 MFC socket编程 有啥区别??

4 TCP与UDP与WebSocket

4 TCP与UDP与WebSocket

4 TCP与UDP与WebSocket

4 TCP与UDP与WebSocket