当前位置:网站首页>websoket封装版 参数配置化 开箱即用
websoket封装版 参数配置化 开箱即用
2022-04-22 23:33:00 【皮皮鱼敲代码】
插播:
遇到很闹心的一件事,之前就写好了一篇关于分享一款在线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 ? 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.checkcontimer = 0; //心跳定时器id
this.checkcontimeout = o && o.checkcontimeout ? 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('HeartBeat');
}, 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.checkcont | Boolean | 心跳检测 | 否 | true | 是否开启心跳检测 |
| o.checkcontimeout | Number | 心跳间隔时间 | 否 | 1000 * 15(秒) | 心跳检测间隔时间 |
注意:
1、 该插件只支持ie10及以上的版本,因为websoket只支持ie10及以上的版本。
2、 该插件只支持H5页面。
如果有帮助,可以点赞+收藏+关注,后续有更多知识与您分享!!!
欢迎加入QQ技术群:568984539,加群备注‘地区-名字-技术类型’,以防乱加。
关于本文,如果任何疑问的可以在评论区留言,我看到就会第一时间回复的。
版权声明
本文为[皮皮鱼敲代码]所创,转载请带上原文链接,感谢
https://blog.csdn.net/qq_42961150/article/details/124303529
边栏推荐
- grid_map(6):grid-mapping-in-ROS编译运行
- 【LeetCode 剑指 Offer 36. 二叉搜索树与双向链表(中等)】
- JS calculate the circumference and area of the circle
- UVM源码解读,UVM-1.2 code review notes
- VsCode使用EmmyLua插件调试Unity工程ToLua代码
- Esp32 (GPIO) - GPIO learning (5)
- Shell script command results are saved to variables with line breaks
- Chenshi industrial machine vision | weld detection solution
- 讀《Software Engineering at Google》(11)
- 读《Software Engineering at Google》(14)
猜你喜欢

unbuntu18.04 安装 gamit10.71 problem solution
[chestnut sugar GIS] the essence of programming - (video notes)
![[Swift]代碼觸發UIButton的點擊事件](/img/23/444cfab44afe32d0476ba26f64bfdf.png)
[Swift]代碼觸發UIButton的點擊事件

【Objective-C 高级编程】—— GCD

VsCode使用EmmyLua插件调试Unity工程ToLua代码

【DVCon2020】基于多线程UVM测试平台的仿真加速方法
![[leetcode refers to the path with a certain value in offer 34. Binary tree (medium)]](/img/3d/efb4114ba00a72ef69089445b15e7f.png)
[leetcode refers to the path with a certain value in offer 34. Binary tree (medium)]

Detailed explanation of SQL language

线程池(通俗易懂)

网狐U3D客户端游戏配置加载失败Couldn‘t connect to server解决
随机推荐
SQL数据库基础知识
[swift] code triggers uibutton click event
[original] [open source] C WinForm DPI adaptive scheme, sunnyui three-step solution
JS has several red, white and black balls, including 25 red and white balls, 31 white and black balls and 28 red and black balls. Find the number of each of the three balls.
Esp32 (GPIO) - GPIO learning (5)
On Spartacus product details page, use outlet to display user-defined data
JSON. In golang Marshall pit
JUC 全套(1)
[PCIe 6.0] new features of PCIe 6.0 - detailed explanation of l0p
Django指定数据库的时候报No module named ‘django_test.settings‘
SQL Net message from client 事件产生的原因分析
Codeforces Round #784 (Div. 4)
JS to traverse the array
【毅力挑战】PCIe 每日一问一答(2022.02 归档)
Webrtc series - webrtc Foundation (VII) NAT, stun and turn (1)
Software test (1)
Cause analysis of SQL net message from client event
华为机试题——HJ76 尼科彻斯定理
[dvcon2020] automatic generation method of UVM sequence based on ral
Enter a formula in the Visio text box