Vue请求WebSocket代码示例

注意:只要连接上,服务端发送消息过来webSocketAcceptMessage()【自定义的函数】会自动接受服务端的信息。

<template>
  <div class="socket1">
    <el-card class="box-card">
      <div slot="header" class="clearfix">
        <span>WebSocket</span>
        <el-button style="float: right; padding: 3px 0" type="text" @click=" webSocketSend(textarea)">发送</el-button>
      </div>
      <div>
       <p>{{msgData}} </p>
      </div>
      <el-input
        type="textarea"
        :rows="2"
        placeholder="请输入内容"
        v-model="textarea">
      </el-input>
    </el-card>

  </div>
</template>

<script>
  export default {
    data(){
      return{
        webSock: null,
        reconnectData:null,
        lockReconnect:false,    //避免重复连接,因为onerror之后会立即触发 onclose
        timeout:600000,          //心跳时间参数  1小时一次心跳检测
        timeoutObj:null,         //心跳检测函数执行后的参数 1代表执行成功
        serverTimeoutObj:null,    //等待服务端响应函数执行后的参数 1代表执行成功
        textarea:'',             //输入框 文字
        msgData:''
      }
    },
    created(){
      if (typeof (WebSocket) === 'undefined') {
        console.log('您的浏览器不支持WebSocket')
      } else {
        // console.log('您的浏览器支持WebSocket')
        this.initWebSocket();
      }

    },
    methods:{
      // WebSockets参数初始化
      initWebSocket(){
        console.log('WebSocket启动中......')
        // let wsurl = 'ws://121.40.165.18:8800';
        //WebSocket服务器地址
        let wsurl = 'ws://127.0.0.1:8087';
        // let wsurl = 'ws://123.207.136.134:9010/ajaxchattest';
        this.webSock = new WebSocket(wsurl);
        this.webSock.onopen = this.webSocketOpen;          //连接成功
        this.webSock.onmessage = this.webSocketAcceptMessage;    //广播成功
        this.webSock.onerror = this.webSocketError;        //连接断开,失败
        this.webSock.onclose = this.webSocketClose;          //连接关闭
      },
      //初始化WebSocket
      webSocketOpen(){
        console.log('连接成功')
        this.heartBeat();
      },           //连接成功
      webSocketError(){
        console.log('连接失败')
        this.reconnect();
      },          //连接失败
      webSocketClose(){
        console.log('断开连接');
        this.reconnect();
      },
      //接受webSocket消息
      webSocketAcceptMessage(evt){
        this.heartBeat();      //收到消息会刷新心跳检测,如果一直收到消息,就推迟心跳发送
        // let msgData = JSON.parse(data);
        console.log('收到消息'+evt.data);
        this.msgData+=evt.data+'\n'
      },
      //发送数据到服务端
      webSocketSend(data){
        this.webSock.send(JSON.stringify(data));
      },
      //重新连接 WebSocket服务
      reconnect(){
        if(this.lockReconnect){       //连接失败和关闭之后都会触发,通过lockReconnect控制只连接了一个webSocket
          return
        }
        this.lockReconnect = true;
        //clearTimeout() 方法可取消由 setTimeout() 方法设置的定时操作。
        // clearTimeout() 方法的参数必须是由 setTimeout() 返回的 ID 值。
        this.reconnectData && clearTimeout(this.reconnectData);
        // setTimeout() 方法用于在指定的毫秒数后调用函数或计算表达式
        //5s后调用initWebSocket()
        //这个函数执行成功 reconnectData会变为1 也就是true
        this.reconnectData = setTimeout(()=>{
          this.initWebSocket();
          this.lockReconnect = false;
        },5000)
      },
      //心跳检测
      heartBeat(){
        this.timeoutObj && clearTimeout(this.timeoutObj);
        this.serverTimeoutObj && clearTimeout(this.serverTimeoutObj);
        this.timeoutObj = setTimeout(()=>{
          this.webSocketSend({type:'心跳检测'})   //根据后台要求发送
          this.serverTimeoutObj = setTimeout(()=> {
            this.webSock.close();  //如果10秒之后我们没有收到 后台返回的心跳检测数据 断开socket,断开后会启动重连机制
          }, 10000);
        }, this.timeout)
      },
    },
    destroyed() {
      this.lockReconnect = true;
      this.webSock.close()                   //离开路由之后断开websocket连接
      clearTimeout(this.reconnectData);      //离开清除 timeout
      clearTimeout(this.timeoutObj);         //离开清除 timeout
      clearTimeout(this.serverTimeoutObj);   //离开清除 timeout
    }
  }
</script>
<style>
  .text {
    font-size: 14px;
  }

  .item {
    margin-bottom: 18px;
  }

  .clearfix:before,
  .clearfix:after {
    display: table;
    content: "";
  }
  .clearfix:after {
    clear: both
  }

  .box-card {
    width: 480px;
  }
  </style>

路由:

 // socket
  {
    path: '/socket',
    name: 'socket1',
    component: () => import(/* webpackChunkName: "about" */ '../components/socket.vue')
  }

开头真难,搞了快一天了,进去了其实很简单,主要是刚开始自己服务端代码写的有问题,头皮发麻

这是个免费的测试网址:ws://123.207.136.134:9010/ajaxchattest

posted @ 2020-04-07 21:16  Angry-rookie  阅读(978)  评论(0)    收藏  举报