当前位置: 首页 > news >正文

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('关闭了')
}

参数说明:

参数名类型说明是否必传默认值备注
urlString连接websoket地址ws类似于http,wss类似于https
o.debugBoolean调试模式false是否开启调试模式
o.resureBoolean断开重连true是否允许断开重连
o.retimeoutNumber断开重连间隔时间1000 * 8(秒)
o.remaxNumber最大重连次数-1(无限制)
o.checkcontSendValueNumber心跳检测发送的值‘checkcont’心跳检测发送的值
o.checkcontBoolean心跳检测true是否开启心跳检测
o.checkcontimeoutNumber心跳间隔时间1000 * 15(秒)心跳检测间隔时间

注意:

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


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

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

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

相关文章:

  • h5页面js监听页面失去焦点、获取焦点
  • uniapp之vuex在vue2和vue3两种模式下前端工程化动态导入文件
  • css实现三角形的最简单方式原理剖析
  • android4.4.2内核移植3.4.1
  • js正则提取字符串中http等地址
  • 解决 多列 布局 左右等高问题
  • unicloud云函数时间慢8小时的解决方案
  • 前端js实现字符转义和反转义
  • 实时数据库:优势和报价
  • 使用express搭建简单的本地服务器
  • 动手动脑
  • 作为程序员,有哪些神级编程资源呢
  • md5加密
  • 闭包得从底层理解
  • Linux wget auto login and backup database
  • [NodeJS] 关于Buffer
  • “寒冬”下的金三银四跳槽季来了,帮你客观分析一下局面
  • 【Under-the-hood-ReactJS-Part0】React源码解读
  • 【个人向】《HTTP图解》阅后小结
  • emacs初体验
  • ES6简单总结(搭配简单的讲解和小案例)
  • express如何解决request entity too large问题
  • Fastjson的基本使用方法大全
  • JavaScript实现分页效果
  • JavaScript异步流程控制的前世今生
  • JS 面试题总结
  • Linux gpio口使用方法
  • Mac 鼠须管 Rime 输入法 安装五笔输入法 教程
  • mockjs让前端开发独立于后端
  • MySQL的数据类型
  • spring boot下thymeleaf全局静态变量配置
  • Vue学习第二天
  • 从零开始的webpack生活-0x009:FilesLoader装载文件
  • 动手做个聊天室,前端工程师百无聊赖的人生
  • 读懂package.json -- 依赖管理
  • 工作中总结前端开发流程--vue项目
  • 码农张的Bug人生 - 初来乍到
  • 学习HTTP相关知识笔记
  • 异步
  • 从如何停掉 Promise 链说起
  • !!java web学习笔记(一到五)
  • #NOIP 2014# day.2 T2 寻找道路
  • #pragma multi_compile #pragma shader_feature
  • #ubuntu# #git# repository git config --global --add safe.directory
  • (Redis使用系列) SpirngBoot中关于Redis的值的各种方式的存储与取出 三
  • (二)Linux——Linux常用指令
  • (附源码)spring boot网络空间安全实验教学示范中心网站 毕业设计 111454
  • (附源码)ssm高校升本考试管理系统 毕业设计 201631
  • (六)软件测试分工
  • (四)鸿鹄云架构一服务注册中心
  • (一)pytest自动化测试框架之生成测试报告(mac系统)
  • (已解决)vue+element-ui实现个人中心,仿照原神
  • (译) 理解 Elixir 中的宏 Macro, 第四部分:深入化
  • (状压dp)uva 10817 Headmaster's Headache
  • .NET WebClient 类下载部分文件会错误?可能是解压缩的锅