vue设置全局webSocket,并在对应页面接受消息通知处理

最近项目中有用到了webSocket,然后在收到消息之后需要在不同的页面进行处理。所有就需要在不同的页面监听并进行对应的消息处理。

首先,在app.vue中添加socket初始化,并设置发送消息,接收消息和心跳检测的处理。

// App.vue
export default {
	data() {
		return {
			// socket参数
			socket: null,
			timeout: 10 * 1000, // 45秒一次心跳
			timeoutObj: null, // 心跳心跳倒计时
			serverTimeoutObj: null, // 心跳倒计时
			timeoutnum: null, // 断开 重连倒计时
			lockReconnect: false, // 防止
			websocket: null
		};
	},
    mounted() {
		this.initWebSocket(userId); // userId为socket链接的参数
	},
    methods:{
        initWebSocket(supplierId) {
			// WebSocket与普通的请求所用协议有所不同,ws等同于http,wss等同于https
			let wsUrl = `wss://192.168.1.33/rest/supplier-api/wss/websocket/${userId}`;
			this.websocket = new WebSocket(wsUrl);
			this.websocket.onopen = this.websocketonopen;
			this.websocket.onerror = this.websocketonerror;
			this.websocket.onmessage = this.setOnmessageMessage;
			this.websocket.onclose = this.websocketclose;
            // 监听窗口关闭事件,当窗口关闭时,主动去关闭websocket连接,防止连接还没断开就关闭窗口,server端会抛异常。
            // window.onbeforeunload = that.onbeforeunload
		},
		start() {
			console.log('start');
			//清除延时器
			this.timeoutObj && clearTimeout(this.timeoutObj);
			this.serverTimeoutObj && clearTimeout(this.serverTimeoutObj);
			this.timeoutObj = setTimeout(() => {
				if (this.websocket && this.websocket.readyState == 1) {
					this.websocket.send('heartBath');//发送消息,服务端返回信息,即表示连接良好,可以在socket的onmessage事件重置心跳机制函数
				} else {
					this.reconnect();
				}
				//定义一个延时器等待服务器响应,若超时,则关闭连接,重新请求server建立socket连接
				this.serverTimeoutObj = setTimeout(() => {
					this.websocket.close();
				}, this.timeout)
			}, this.timeout)
		},
		reset() { // 重置心跳
			// 清除时间
			clearTimeout(this.timeoutObj);
			clearTimeout(this.serverTimeoutObj);
			// 重启心跳
			this.start();
		},
		// 重新连接
        reconnect() {
			if (this.lockReconnect) return
			this.lockReconnect = true;
			//没连接上会一直重连,设置延迟避免请求过多
            this.timeoutnum && clearTimeout(this.timeoutnum);
            this.timeoutnum = setTimeout(() => {
				this.initWebSocket();
                this.lockReconnect = false;
            }, 5000)
        },
		async setOnmessageMessage(event) {
			console.log(event.data, '获得消息');
			this.reset();
			// 自定义全局监听事件
			window.dispatchEvent(new CustomEvent('onmessageWS', {
				detail: {
					data: event.data
				}
			}))
			// //发现消息进入    开始处理前端触发逻辑
			// if (event.data === 'success' || event.data === 'heartBath') return
        },
		websocketonopen() {
            //开启心跳
            this.start();
            console.log("WebSocket连接成功!!!"+new Date()+"----"+this.websocket.readyState);
		},
		websocketonerror(e) {                
			console.log("WebSocket连接发生错误" + e);              
		},
		websocketclose(e) {
            this.websocket.close();
            clearTimeout(this.timeoutObj);
			clearTimeout(this.serverTimeoutObj);
            console.log("WebSocket连接关闭");
		},
        websocketsend(messsage) {
            that.websocket.send(messsage)
        },
        closeWebSocket() { // 关闭websocket
            that.websocket.close()
        },
    }

其中:在接收到消息之后需要自定一个监听事件,来供页面去监听消息通知。

async setOnmessageMessage(event) {
	console.log(event.data, '获得消息');
	this.reset();
	// 自定义全局监听事件
	window.dispatchEvent(new CustomEvent('onmessageWS', {
		detail: {
			data: event.data
		}
	}))
	// //发现消息进入    开始处理前端触发逻辑
	// if (event.data === 'success' || event.data === 'heartBath') return
},

最后在需要使用的页面添加监听事件

mounted () {
	// 添加socket通知监听
	window.addEventListener('onmessageWS', this.getSocketData)
},
methods: {
    // 收到消息处理
	getSocketData (res) {
		if (res.detail.data === 'success' || res.detail.data === 'heartBath') return
		// ...业务处理
	},
}

至此,vue配置全局socket的需求就完成了。欢迎大佬们一起讨论

  • 16
    点赞
  • 78
    收藏
    觉得还不错? 一键收藏
  • 打赏
    打赏
  • 18
    评论

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

inticaler

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值