基于calss封装一个websocket

写一个webscoket.js文件
 

class WebSocketClass {
    constructor(url = '', webSocketError = 0, callback = () => { }) {
        this.instance = null;
        this.callback = callback; // 回调函数
        this.wsurl = url; // ws路径
        this.webSocketError = webSocketError // 初始化重连次数
        this.webSocketErrorMax = 10 // 最大的重连次数
        this.socketInit(url);
    }
    static getInstance() {
        if (!this.instance) {
            this.instance = new WebSocketClass(this.wsurl, this.webSocketError, this.callback);
        }
        return this.instance;
    }
    // 初始化socke
    socketInit(url) {
        if (url != undefined) {
            this.ws = new WebSocket(url);
            this.ws.onopen = e => {
                this.status = 'open';
                console.log(`连接成功`, e);
                this.getMessage();
            };
            this.ws.onclose = msg => {
                console.log(msg, 'oncloseonclose');
                // 重连
                if (this.webSocketError < this.webSocketErrorMax) {
                    setTimeout(() => {
                        this.socketInit(this.wsurl)
                    }, 500)
                } else {
                    console.log('组件销毁或者重连数次过多');
                }
            }
            this.ws.onerror = err => {
                this.webSocketError++
                console.log(err, 'onerroronerror');
            }
        }
    }
    // 接受消息
    getMessage() {
        this.ws.onmessage = e => {
            this.callback(e.data)
        }
    }
    // 手动关闭socket
    close() {
        this.status = 'close';
        this.ws.send('close');
        this.webSocketError = 89
        this.ws.close();
    }
}
export default WebSocketClass;

使用封装的websocket

<script>
  import WebSocketClass from "@/common/websocket";
  export default {
    props: {},
    data() {
      return {
        homeWs: null,
      };
    },
    computed: {
    },
    created() {
    },
    mounted() {
      this.init();
    },
    watch: {
    },
    methods: {
      init() {
        this.homeWs = new WebSocketClass("ws://xxxxxxxxx", 0, msg => {
          console.log(msg)
        });
      }
    },
    components: {},
    destroyed() {
      this.homeWs.close();
    }
  };
</script>

 

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

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值