在Vue中使用websocket实时通信


描述

前端中实现实时通信必须用到websocket,通常前端vue项目中会有多个不同的路由页面,为了保证整个项目中共用一个相同的websocket连接,需要在App.vue中实例化websocket对象。同时,复杂的网络环境难以判断长连接的状态,需要有心跳包以及重连机制。


一、构建一个全局的global.js文件

新建一个名为global.js的文件

// global.js
export default {
    ws: {},//websocket对象
    delay:1500,//重连延迟,单位:毫秒
    //设置websocket对象方法
    setWs: function(newWs) {
        this.ws = newWs
    },
    //设置延迟方法
    setDelay:function(newDelay){
    	 this.delay = newDelay
    },
    //发送websocket信息方法
    sendMsg:function(message){
    	this.ws.send(JSON.stringify(message))
    },
}

二、使用步骤

1.引入global.js

在main.js中引入global.js,代码如下(示例):

import global from './components/global.js'
//命名并设置全局变量
Vue.prototype.$global = global

2.实例化webscoekt

创建一个creatSocket()方法(示例):

creatSocket() {
	 let that = this;
	  if ("WebSocket" in window) {
		 console.log("您的浏览器支持 WebSocket!");	
		 //实例化websocket	 
		 that.ws = new WebSocket("ws://192.168.1.1:8008");
		        //保存设置全局websocket对象
			    that.$global.setWs(that.ws);
			    //监听websocket连接打开方法
			    that.ws.onopen = function() {
			    	console.log("打开websocket")
			    	//调用keepalive方法(不一定都需要调用此方法,可注释)
			    	//that.keepAlive()
			    }
			    //监听websocket错误方法
				that.ws.onerror = function(ev) {
					 console.log("连接已出错...");
				   	 //延迟执行重连
				      setTimeout(() => {
				        that.creatSocket();
				      }, that.$global.delay);
				};
				//监听websocket关闭方法
			    that.ws.onclose = function(ev) {
				      // 关闭 websocket
				      console.log("连接已关闭...");
				   	 //延迟执行重连
				      setTimeout(() => {
				        that.creatSocket();
				      }, that.$global.delay);
			    };
			    
			    //监听websocket接收消息事件(接收来自服务器的实时消息)
			    that.ws.onmessage = function(res) {
				    console.log("App.vue收到服务器内容", res.data);
				  };
			    
			  } else {
			    // 浏览器不支持 WebSocket
			    console.log("您的浏览器不支持 WebSocket!");
			  }
},

3.心跳机制

为了防止后端无法检测连接无故被中断,通常前端会和后端约定一个心跳包的发送机制(即每隔一定时间发送一个约定请求到后端),以保证后端实时知道当前连接状态
[注意:发送内容需要和后端约定,这里只是示例]

keepAlive(){
	let that = this;
	  setTimeout(() => {
	     //判断当前webscokt状态
		 if(that.$global.ws.readyState == 1){
				console.log('发送keepalve')
				//调用发送方法
				that.$global.sendMsg({
						"type":"keepalive"
				})
				that.keepAlive()			 		
		}
		 }, 10000);				
},

4.其它路由页面使用webscoekt

页面mounted的时候触发监听方法this.eventMsg()

mounted() {
	this.eventMsg()
},
methods:{
	eventMsg(){
		let that = this;
		this.$global.ws.onmessage = function(res) {
				//处理接收的时间逻辑
		}
	}
}

发送请求方法

if(this.$global.ws && this.$global.ws.readyState == 1) {	
	this.$global.sendMsg({
		//参数内容
	})
}

  • 5
    点赞
  • 75
    收藏
    觉得还不错? 一键收藏
  • 5
    评论
评论 5
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值