class Socket {
constructor(params) {
window.WebSocket = window.WebSocket || window.MozWebSocket;
if (!window.WebSocket) {
console.error('错误: 浏览器不支持websocket');
return;
}
this.websocket = null;
this.params = params;
this.socketInit(params);
}
socketInit({
url, onopen, onmessage, onerror, onclose, reconnect = false, timer,
}) {
if (url !== undefined) {
if (!/^wss?:\/\//.test(url)) {
const { protocol } = window.location;
url = protocol === 'http:' ? 'ws://' + url : 'wss://' + url;
}
try {
this.websocket = new WebSocket(url);
this.websocket.onopen = (e) => {
console.log('连接成功', e);
if (timer > 0) {
this.heartCheck(timer);
}
if (typeof onopen === 'function') {
onopen(e);
}
};
this.websocket.onmessage = (e) => {
console.log('接收数据', e);
onmessage(e.data);
};
this.websocket.onclose = (e) => {
console.log('连接关闭', e);
reconnect && this.reconnect();
if (typeof onclose === 'function') {
onclose(e);
}
};
this.websocket.onerror = (e) => {
console.log('连接异常', e);
reconnect && this.reconnect();
if (typeof onerror === 'function') {
onerror(e);
}
};
} catch (e) {
reconnect && this.reconnect();
}
}
}
send(message) {
if (!this.websocket || this.websocket.readyState !== 1) {
console.log('请确认websocket是否已经链接并且可以通讯');
return;
}
this.websocket.send(JSON.stringify(message));
}
close() {
this.heartInterval && clearInterval(this.heartInterval);
this.reconnectTimeout && clearTimeout(this.reconnectTimeout);
if (!this.websocket) {
console.log('websocket 不可用');
return;
}
this.websocket.close();
}
heartCheck(timer) {
this.heartInterval = window.setInterval(() => {
this.send({ type: 'ping' });
}, timer);
}
reconnect() {
if (this.lockReconnect) return;
this.lockReconnect = true;
this.reconnectTimeout && clearTimeout(this.reconnectTimeout);
this.reconnectTimeout = window.setTimeout(() => {
this.socketInit(this.params);
this.lockReconnect = false;
}, 5000);
}
}
export default Socket;