websocket实现心跳连接
在使用websocket的时候,遇到了一个websocket在连接一段时间就异常断开连接了。第一想法就是重新去连接websocket(websock.onopen),后来发现这种方式是错误的,查阅文档发现,要想重新建立连接,就需要一种心跳思想去处理(实时监听连接情况,断了就去重连)
下面以Vue代码为准:
let lockReconnect = false;//避免重复连接
let wsUrl = '‘ // url;
let ws;
let tt;
createWebSocket() {
let that = this;
try {
ws = new WebSocket(wsUrl);
this.init();
} catch(e) {
console.log('catch');
that.reconnect(wsUrl);
}
},
init() {
let that = this;
//心跳检测
let heartCheck = {
timeout: 3000,
timeoutObj: null,
serverTimeoutObj: null,
start: function(){
console.log('start');
let self = this;
this.timeoutObj && clearTimeout(this.timeoutObj);
this.serverTimeoutObj && clearTimeout(this.serverTimeoutObj);
this.timeoutObj = setTimeout(function(){
//这里发送一个心跳,后端收到后,返回一个心跳消息,
console.log('55555');
ws.send("888");
self.serverTimeoutObj = setTimeout(function() {
console.log(111);
console.log(ws);
ws.close();
// createWebSocket();
}, self.timeout);
}, this.timeout)
}
};
ws.onclose = function () {
console.log('链接关闭');
that.reconnect(wsUrl);
location.reload()
};
ws.onerror = function() {
console.log('发生异常了');
that.reconnect(wsUrl);
location.reload();
};
ws.onopen = function () {
//心跳检测重置
heartCheck.start();
};
ws.onmessage = function (e) {
//拿到任何消息都说明当前连接是正常的
console.log('接收到消息');
console.log(e);
heartCheck.start();
}
},
reconnect(url) {
if(lockReconnect) {
return;
}
lockReconnect = true;
//没连接上会一直重连,设置延迟避免请求过多
tt && clearTimeout(tt);
tt = setTimeout( () => {
this.createWebSocket(url);
lockReconnect = false;
}, 4000);
},
this.createWebSocket(wsUrl);
最新文章
- 修改ArcGIS Server Account / 站点管理员的 账号、密码
- Fast-cgi cgi nginx php-fpm 的关系 (转
- Android SQLite数据储存方式
- Ubuntu 关闭锁屏界面的 on-screen keyboard
- NOSQL之【redis的安全策略】
- fork()和vfork()区别
- 请给出异步加载js方案
- SQL服务器名称更改
- sql 练习(3)
- 浅析NopCommerce的多语言方案
- WebService调用(基于KSOAP2)
- JavaScript实现ZLOGO: 用语法树实现多层循环
- CSS选取第n个标签元素
- mysql join用法简介
- linux 学习之路:ls命令使用
- 遭遇ASP.NET的Request is not available in this context
- netty 的 JBoss Marshalling 编码解码
- Chrome驱动安装问题
- Express 开发与部署最佳实践 -- 待续
- Java设计模式百例 - 观察者模式
热门文章
- Spring MVC -- 验证器
- Python 内置函数--range() xrange()
- 阿里P8架构师谈:阿里双11秒杀系统如何设计?
- Java开发笔记(一百一十一)POST方式的HTTP调用
- 二、SpringBoot基础配置
- Delphi 10.2 JSON与对象/结构体序列化性能提高100多倍
- 函数的学习2——返回值&;传递列表——参考Python编程从入门到实践
- UI单据字段值查看方式
- module 'pip._internal' has no attribute 'pep425tags'
- Spring Cloud Alibaba学习笔记(22) - Nacos配置管理