直接上代码
var _this = '';
function socket(url) {
this.url = url;
this.websocket = '';
this.msg = '';
this.lockReconnect = false;
}
// 初始化
socket.prototype.initWebsocket = function() {
if ('WebSocket' in window) {
_this = this;
this.websocket = new WebSocket(this.url);
this.websocket.onerror = this.onError;
this.websocket.onmessage = this.onMessage;
this.websocket.onopen = this.onOpen;
this.websocket.onclose = this.onClose;
} else {
console.log('错误:浏览器不支持websocket,请更换新版浏览器');
}
}
// 连接异常处理
socket.prototype.onError = function() {
_this.msg = "websocket错误," + new Date().toTimeString() + " 状态码:" + _this.websocket.readyState;
console.warn(_this.msg);
// 重新连接
_this.reconnect();
}
// 接收到消息处理
socket.prototype.onMessage = function(event) {
if (event.data == 'ok') {
heartCheck.start();
return;
}
window.dispatchEvent(new CustomEvent('onmessageWS', {
detail: {
data: event.data
}
}))
// 通过下面接受消息 下面这个在其他js里
// window.addEventListener("onmessageWS", function(e) {
// console.log(e.detail)
// })
}
// 关闭连接处理
socket.prototype.onClose = function(e) {
_this.msg = "websocket断开连接:" + new Date().toTimeString();
console.log(_this.msg);
console.log('日志:' + e.code + ' ' + e.reason + ' ' + e.wasClean);
if (e.code != 1000 && e.code != 1006) {
// 重新连接
_this.reconnect();
}
}
// 打开连接处理
socket.prototype.onOpen = function() {
_this.msg = "websocket连接成功," + new Date().toTimeString() + " 状态码:" + _this.websocket.readyState;
console.log(_this.msg);
_this.websocket.send('加入websocket连接');
// 心跳检测重置
heartCheck.start();
}
// 主动关闭连接
socket.prototype.close = function() {
// 关闭socket连接
_this.websocket.close();
_this.lockReconnect = true;
}
// socket 重连
socket.prototype.reconnect = function() {
// 已经重连则取消后续操作
if (_this.lockReconnect) return;
_this.lockReconnect = true;
// 没连接上会一直重连,设置延迟避免请求过多
tt && clearTimeout(tt);
_this.msg = '正在进行重连:' + new Date().toTimeString();
console.log(_this.msg);
var tt = setTimeout(function() {
_this.initWebsocket();
_this.lockReconnect = false;
}, 5000);
}
let heartCheck = {
timeout: 5000,
timeoutObj: null,
serverTimeoutObj: null,
start: function() {
let self = this;
this.timeoutObj && clearTimeout(this.timeoutObj);
this.serverTimeoutObj && clearTimeout(this.serverTimeoutObj);
this.timeoutObj = setTimeout(function() {
console.log('check socket heart beat……');
//发送测试信息,后端收到后,返回一个消息,
_this.websocket.send("ping");
self.serverTimeoutObj = setTimeout(function() {
_this.websocket.onerror();
}, self.timeout)
}, this.timeout);
}
}
export { socket }
调用
sk = new socket(`ws://255,255,255,255:8080/socket/xxxx`);
sk.initWebsocket();