欢迎来到尧图网

客户服务 关于我们

您的位置:首页 > 财经 > 金融 > 组件化 websocket

组件化 websocket

2025/6/19 23:24:47 来源:https://blog.csdn.net/qq_35227244/article/details/148634523  浏览:    关键词:组件化 websocket

实时数据响应,组件化websocket减少代码冗余

组件定义 websocket.vue

<template><div></div>
</template><script>export default {data() {return {webSocket: null, // webSocket实例lockReconnect: false, // 重连锁,避免多次重连maxReconnect: 3, // 最大重连次数, -1 标识无限重连reconnectTime: 0, // 重连尝试次数};},created() {this.initWebSocket()},destroyed: function () {this.webSocket.close()},//方法集合methods: {/*** 初始化 weoSocket*/initWebSocket() {// ws地址 const host = 'XXXXXXX'const wsUri = `ws://${host}:3000`console.log(wsUri)// 建立连接this.webSocket = new WebSocket(wsUri)// 连接成功this.webSocket.onopen = this.onOpen// 连接错误this.webSocket.onerror = this.onError// 接收信息this.webSocket.onmessage = this.onMessage// 连接关闭this.webSocket.onclose = this.onClose},/*** 连接成功事件*/onOpen() {console.log('WebSocket connection success')this.reconnectTime = 0},/*** 数据发送* @param msg*/send(msg) {//数据发送this.webSocket.send(msg)console.log('Websocket send:',msg)},/*** 连接失败事件* @param e*/onError(e) {//错误console.log(`WebSocket connection error:${e.code} ${e.reason} ${e.wasClean}`)//重连// this.reconnect()},/*** 连接关闭事件* @param e*/onClose(e) {//关闭console.log(`WebSocket connection closed:${e.code} ${e.reason} ${e.wasClean}`)//重连// this.reconnect()},/*** 重新连接*/reconnect() {if (this.lockReconnect || (this.maxReconnect !== -1 && this.reconnectTime > this.maxReconnect)) {return}this.lockReconnect = truesetTimeout(() => {this.reconnectTime++// 建立新连接this.initWebSocket()this.lockReconnect = false}, 5000)},/*** 接收服务器推送的信息* @param msgEvent*/onMessage(msgEvent) {// console.log('日志信息打印:',msgEvent)this.$emit('onMessage', msgEvent.data)},},}
</script>

组件引用

        <myWebsocket v-if="dialogVisible" @onMessage="getMsg" />

版权声明:

本网仅为发布的内容提供存储空间,不对发表、转载的内容提供任何形式的保证。凡本网注明“来源:XXX网络”的作品,均转载自其它媒体,著作权归作者所有,商业转载请联系作者获得授权,非商业转载请注明出处。

我们尊重并感谢每一位作者,均已注明文章来源和作者。如因作品内容、版权或其它问题,请及时与我们联系,联系邮箱:809451989@qq.com,投稿邮箱:809451989@qq.com

热搜词