websocket+ts通用组件
export default function socket(ws_url: string) {
const socket = {
websock: null as any,
ws_url,
socket_open: false,
hearbeat_timer: null as any,
hearbeat_interval: 5000,
is_reonnect: true,
reconnect_count: 3,
reconnect_current: 1,
reconnect_timer: null as any,
reconnect_interval: 3000,
init: (cb?: any) => {
if (!("WebSocket" in window)) {
console.log("浏览器不支持WebSocket");
return null;
}
if (socket.websock) {
return socket.websock;
}
socket.websock = new WebSocket(socket.ws_url);
socket.websock.onmessage = (e: any) => {
socket.receive(e, cb);
};
socket.websock.onclose = (e: { code: any }) => {
console.log("连接已断开");
console.log(`connection closed (${e.code})`);
clearInterval(socket.hearbeat_interval);
socket.socket_open = false;
if (socket.is_reonnect) {
socket.reconnect_timer = setTimeout(() => {
if (socket.reconnect_current > socket.reconnect_count) {
clearTimeout(socket.reconnect_timer);
return;
}
socket.reconnect_current += 1;
socket.reconnect();
}, socket.reconnect_interval);
}
};
socket.websock.onopen = () => {
console.log("连接成功");
socket.socket_open = true;
socket.is_reonnect = true;
socket.heartbeat();
};
socket.websock.onerror = () => {
console.log("WebSocket连接发生错误");
};
},
send: (data: any, callback: any = null) => {
if (socket.websock.readyState === socket.websock.OPEN) {
socket.websock.send(JSON.stringify(data));
if (callback) {
callback();
}
} else if (socket.websock.readyState === socket.websock.CONNECTING) {
setTimeout(() => {
socket.send(data, callback);
}, 1000);
} else {
socket.init();
setTimeout(() => {
socket.send(data, callback);
}, 1000);
}
},
receive: (message: any, cb: any) => {
try {
const params = JSON.parse(message.data);
if (params !== null) {
cb && cb(params);
}
} catch (error) {
console.log(error);
}
},
heartbeat: () => {
console.log("socket", "ping");
if (socket.hearbeat_timer) {
clearInterval(socket.hearbeat_timer);
}
socket.hearbeat_timer = setInterval(() => {
const data = null;
socket.send(data);
}, socket.hearbeat_interval);
},
close: () => {
console.log("主动断开连接");
clearInterval(socket.hearbeat_interval);
socket.is_reonnect = false;
socket.websock.close();
},
reconnect: () => {
console.log("发起重新连接", socket.reconnect_current);
if (socket.websock && socket.socket_open) {
socket.websock.close();
}
socket.websock = null;
socket.init();
},
};
return socket;
}