vue结合websocket

1. vue结合websocket
本人首先是写java后端的,我也是第一次接触websocekt,当然前端也接触的也少,但是楼主已经默默的学会了flex布局,下面的是做的测试页面,写的不好还请谅解。下面时本人总结的websocket可以直接复制拿去用,当然这里说的是前端。这里后端用的netty,后端就不贴源码了,怕被同事看到。项目用的是诺伊框架,

2.上干货 前端websocket

<template>
  <div class="test">
    {{redata1.userId}}
  </div>
</template>

<script>
  export default {
    name : 'test',
    data() {
      return {
        websock: null,
        timer:undefined,
        redata1:{
          userId:undefined
        },
     
        dataping:{
              heartbeat:"心跳"
          },
        sendform:{
          userId:"123456"
        }
          
      }
        
      
    },
    created() {
      if(window.WebSocket){
      this.websock = new WebSocket("ws://127.0.0.1:58080/webSocket");
      this.initWebSocket();
      }else{
        alert("浏览器不支持websocket")
      }
     
  
    },
    destroyed() {
      clearInterval(this.timer)
      this.websock.close() //离开路由之后断开websocket连接
    },
    mounted(){
    //   const timer = setInterval(()=>{
      //    // 这里调用调用需要执行的方法,1为自定义的参数,由于特殊的需求它将用来区分,定时器调用和手工调用,然后执行不同的业务逻辑
    //          this.websocketonopen();
    //   }, 3000) // 每两秒执行1次
   },
    methods: {
   
      initWebSocket(){ //初始化weosocket
        console.log(this.websock)
        this.websock.onmessage = this.websocketonmessage;
        this.websock.onopen = this.websocketonopen;
        this.websock.onerror = this.websocketonerror;
        this.websock.onclose = this.websocketclose;
      },

      websocketonopen(){ //连接建立之后执行send方法发送数据
        let actions = this.sendform
        this.websocketsend(JSON.stringify(actions));
        this.sendPing();
      },
      
      sendPing(){
        this.timer = setInterval(()=>{
        let actions = this.dataping
          this.websock.send(JSON.stringify(actions));
       },5000)
      },

      websocketonerror(){//连接建立失败重连
        this.initWebSocket();
      },
      websocketonmessage(e){ //数据接收
     
      if(e.data=="心跳连接存在"||e.data=="服务器连接成功"){
        console.log(e.data)
      }else{
        this.redata1 = JSON.parse(e.data)
        console.log("11111111111---------"+this.redata1.userId)
      }
      },
     
      websocketsend(Data){//数据发送
        this.websock.send(Data);
      },
      websocketclose(e){  //关闭
        console.log('断开连接',e);
      },
    },
  }
</script>

<style scoped lang="scss">
.test{
  height: calc(100vh - 84px);
  width: 100%;
  display: flex;
}
</style>

  • 2
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值