uniapp中建立websocket连接

1、新建websocket.js

import store from '@/store'

export default class WebsocketTask{
  constructor(url,time){
    this.url = url
    this.data = null
    this.isOpenSocket = false
    // 心跳检测
    this.timeout = time
    this.heartbeat = null
    try{
      return this.connectSocketInit()
    }catch(e){
      this.isOpenSocket = false
      this.reconnect();
    }
  }

  connectSocketInit(){
    this.socketTask = uni.connectSocket({
      url: this.url,
      header: {
        'Authorization':'Bearer '+ store.state.user.token
      },
      success:(success)=>{
        console.log(success)
      },
      fail:(fail)=>{
        console.log(fail)
      },
      complete: (complete)=> {
        console.log(complete)
      }
    })

    this.socketTask.onOpen((res)=>{
      clearTimeout(this.heartbeat);
      this.isOpenSocket = true;
      this.start();
      this.socketTask.onMessage((res)=>{
        console.log(res)
      })
    })

    this.socketTask.onClose(()=>{
      this.isOpenSocket = false;
      this.reconnect();
    })
  }

  //发送消息
  send(data){
    this.socketTask.send({
      data,
    })
  }

  //开启心跳检测
  start(){
    this.heartbeat = setTimeout(()=>{
      this.data = {value:'开始心跳检测'}
      this.send(JSON.stringify(this.data));
    }, this.timeout)
  }

  // 重新连接
  reconnect(){
    clearInterval(this.heartbeat)
    if(!this.isOpenSocket){
      setTimeout(()=>{
        this.connectSocketInit();
      }, 3000)
    }
  }
}

2、在main.js中全局挂载

import WebsocketTask from './utils/websocket.js'
//自行修改请求地址
let websocket = new WebsocketTask('ws://xx.xx.xx.xx:xx/',5000)
// 挂载到全局
Vue.prototype.$websocket = websocket;

3、在组件中调用

<template>
    <u-button @click="test" type="primary">测试websocket</u-button>
</template>

<script>
	export default {
		data() {
			return {
			}
		},
		methods: {		
	      test(){
	        let data = {value:'发送的消息'};
	        this.$websocket.send(JSON.stringify(data))
	      }
		}
	}
</script>

<style lang="scss" scoped>
</style>
  • 0
    点赞
  • 6
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值