websoket封装版 参数配置化 开箱即用

插播:

遇到很闹心的一件事,之前就写好了一篇关于分享一款在线ps的软件,无奈一直审核不通过,说是打广告。我修改了多次,还是通不过,好吧,需要的可以加群获取吧。

进入正题:

最近在做项目的时候自己封装了websoket,简单的实现了消息的接收和发送,断线重连、心跳检测等功能。

做之前在网上找了一些相关资料,并没有找到完整的代码,都只是只言片语,不是我想要的,于是对websoket进行了封装,相对而言还是比较完整,那就分享给大家吧。

话不多说,直接上代码~

websoket.js:

var websoket = {
	create: function (url, o) {
		this.hasWebsoket = window.WebSocket && window.WebSocket.prototype.send; //是否支持websoket
		this.connectUrl = url; //连接地址
		this.socketTask = null; //websoket对象
		this.resure = o && o.resure == false ? o.resure : true; // 断开后是否允许重连
		this.relocal = false; // 重连开关
		this.retimer = 0; // 重连定时器id
		this.retimeout = o && o.retimeout ? 1000 * o.retimeout : 1000 * 5; // 重连间隔时间
		this.renum = 0; // 重连次数
		this.remax = o && o.remax ? o.remax : -1; // 最大重连次数 -1代表无限制
		this.checkcont = o && o.checkcont == false ? o.checkcont : true; // 是否开启心跳检测
		this.checkcontSendValue = o && o.checkcontSendValue ? o.checkcontSendValue : 'checkcont'; // 心跳检测发送的值
		this.checkcontimer = 0; //心跳定时器id
		this.checkcontimeout = o && o.checkcontimeout ? 1000 * o.checkcontimeout : 1000 * 15; //心跳间隔时间
		this.debug = o && o.debug ? o.debug : false;
		this.connecting = false; //是否在连接中...
		this.isopen = false; //是否打开状态
		return this;
	},
	// 打印日志
	log: function (msg, res) {
		if (this.debug) {
			if (res) console.log(msg, res);
			else console.log(msg);
		}
	},
	// 打开websoket
	open: function () {
		this.close();
		this.initwebsoket();
	},
	// 初始化websoket
	initwebsoket: function () {
		var that = this;
		// 判断状态是否进行连接websoket
		if (this.connecting || this.isopen) return false;
		this.connecting = true;
		this.isopen = false;
		if (this.hasWebsoket) { //支持websoket
			// this.url = (this.url.slice(0, 5) === 'https') ? 'wss' + this.url.slice(5) : 'ws' + this.url.slice(4);
			this.socketTask = new WebSocket(this.connectUrl);
			if (this.socketTask) this.connecting = false;
			this.socketTask.onopen = function () {
				that.log('---websoket连接成功---');
				that.isopen = true;
				that.renum = 0;
				that.resure = true;
				that.onconsuccess();
				that.checkconnect();
			}
			this.socketTask.onmessage = function (res) {
				that.getMessage(res);
				that.checkconnect();
			}
			this.socketTask.onerror = function (error) {
				that.log('---websoket进入onerror回调,表示连接失败---:', error);
				that.isopen = false;
				that.socketTask = null;
				that.reconnect();
			}
			this.socketTask.onclose = function () {
				that.log('---websoket进入onclose回调,表示已关闭---');
				that.isopen = false;
				that.socketTask = null;
				that.reconnect();
				that.onclose();
			}
		} else { //不支持websoket
			console.warn('浏览器版本过低,不支持websoket');
		}
	},
	// 连接成功回调
	onconsuccess: function () { },
	// 关闭websoket
	close: function () {
		if (!this.socketTask) return false;
		this.socketTask.close();
		this.socketTask = null;
		this.resure = false;
		this.clear();
	},
	// 关闭回调
	onclose: function () { },
	// 发送消息
	send: function (msg) {
		if (!this.isopen) return this.log('请先调用 open() 开启网络');
		this.socketTask.send(JSON.stringify(msg));
	},
	// 处理收到的消息
	getMessage: function (res) {
		try {
			var resultObj = JSON.parse(res.data);
			this.log('---接收到的消息---:', resultObj);
			this.onmessage(resultObj);
		} catch (e) {
			console.error('返回数据出现异常', e);
			this.onmessage(res);
		}
	},
	// 接受消息回调
	onmessage: function (data) { },
	// 重连
	reconnect: function () {
		var that = this;
		if (this.relocal || !this.resure) return false;
		this.relocal = true;
		this.log('开始重连...');
		this.clear();
		this.renum++;
		if (this.remax > -1 && this.renum >= this.remax) return false;
		this.retimer = setTimeout(function () {
			that.initwebsoket();
			that.relocal = false;
		}, this.retimeout)
	},
	// 心跳检测
	checkconnect: function () {
		var that = this;
		if (!that.socketTask || !this.checkcont) return false;
		this.clear();
		this.checkcontimer = setInterval(function () {
			that.log('心跳检测...');
			that.socketTask.send(JSON.stringify(that.checkcontSendValue));
		}, this.checkcontimeout);
	},
	// 清除
	clear: function () {
		this.checkcontimer && clearInterval(this.checkcontimer);
		this.retimer && clearTimeout(this.retimer);
	}
}

使用方法:

<script type="text/javascript" src="websoket.js"></script>
var WebSoket = websoket.create('ws://192.168.0.212:5200', { debug: true });
WebSoket.open();
// 连接成功
WebSoket.onconsuccess = function () {
    console.log('连接成功的后续操作')
}
// 收到消息监听
WebSoket.onmessage = function (res) {
    console.log('收到消息',res)
}
// 关闭监听
WebSoket.onclose = function () {
    console.log('关闭了')
}

参数说明:

参数名 类型 说明 是否必传 默认值 备注
url String 连接websoket地址 ws类似于http,wss类似于https
o.debug Boolean 调试模式 false 是否开启调试模式
o.resure Boolean 断开重连 true 是否允许断开重连
o.retimeout Number 断开重连间隔时间 1000 * 8(秒)
o.remax Number 最大重连次数 -1(无限制)
o.checkcontSendValue Number 心跳检测发送的值 ‘checkcont’ 心跳检测发送的值
o.checkcont Boolean 心跳检测 true 是否开启心跳检测
o.checkcontimeout Number 心跳间隔时间 1000 * 15(秒) 心跳检测间隔时间

注意:

1、 该插件只支持ie10及以上的版本,因为websoket只支持ie10及以上的版本。
2、 该插件只支持H5页面。


如果有帮助,可以点赞+收藏+关注,后续有更多知识与您分享!!!

欢迎加入QQ技术群:568984539,加群备注‘地区-名字-技术类型’,以防乱加。

关于本文,如果任何疑问的可以在评论区留言,我看到就会第一时间回复的。

猜你喜欢

转载自blog.csdn.net/qq_42961150/article/details/124303529