什么?你问我什么是webSocket?那就先去了解什么是socket后再来看这篇文章吧;
开始…
首先 创建 Socket 和 心跳定时器
let Socket = null;//Socket对象
let timingSocketPushTimer = null;//心跳定时器
导出创建Socket的方法
export const createSocket = url=>{
if(url === null) return;//判断Url时候为空
Socket && Socket.close();//如果已经创建了,先关闭当前连接
if(!Socket){
console.log('Create Socket...');
Socket = new WebSocket(`${url}`);
Socket.onopen = openSocket;
Socket.onmessage = SocketOnMessage;
Socket.onerror = SocketOnError;
Socket.onclose = SocketOnClose;
}else
console.log('Socket Connection...')
}
定义openSocket方法
const openSocket = () =>{
sendPing();//开始发送心跳
}
//定义Socket收到消息方法
const SocketOnMessage = (msg) =>{
//此处创建了一个全局监听器,来获取Socket消息
//如果你是例如vue的项目,可以使用vuex的Store
return window.dispatchEvent(new CustomEvent('socketOnMessage', {
data: JSON.parse(msg),
}));
}
定义Socket错误方法
const SocketOnError = () => {
Socket.close();
clearInterval(timingSocketPush);
console.log('Socket Reconnect...');
if (Socket.readyState !== 3) {
Socket = null;
createSocket();//重新连接
}
}
定义 等待消息发送方法
const awaitMessageSend = msg => {
setTimeout(() => {
//判断Socket的状态,为连接状态后 方可发送消息
Socket.readyState === 0 ? awaitMessageSend(msg) : Socket.send(anyToString(msg));
})
}
定义Socket被关闭方法
const SocketOnClose = () => {
clearInterval(timingSocketPush);
console.log('SocketDisconnect,Reconnect...');
if (Socket.readyState !== 2) {
Socket = null;
//重新连接
createSocket();
}
}
导出Socket心跳方法
export const sendPing = (duration = 10000, str = 'ping') => {
clearInterval(timingSocketPush);
Socket.send(anyToString(str));
timingSocketPush = setInterval(() => {
Socket.send(anyToString(str));
}, duration);
}
最后一步 导出 推送消息 方法
export const pushMessage = msg => {
if(typeOf msg !== 'string')
return;
if (Socket !== null && Socket.readyState === 3) {
Socket.close();
createSocket();
} else if (Socket.readyState === 1)
Socket.send(anyToString(msg));
else if (Socket.readyState === 0)
awaitMessageSend(msg);
}
好了,完事,完整代码如下:
/**
* @author ayuanlmo
* Created by ayuanlmo in 2021/07
* **/
let Socket = null;
let timingSocketPush = null;
export const createSocket = url => {
Socket && Socket.close();
if (!Socket) {
console.log('Create Socket...');
Socket = new WebSocket(`${url}`);
Socket.onopen = openSocket;
Socket.onmessage = SocketOnMessage;
Socket.onerror = SocketOnError;
Socket.onclose = SocketOnClose;
} else
console.log('Socket Connection...');
}
const openSocket = () => {
sendPing();
}
const SocketOnMessage = (e) => {
return window.dispatchEvent(new CustomEvent('socketOnMessage', {
data: JSON.parse(e),
}));
}
const SocketOnError = () => {
Socket.close();
clearInterval(timingSocketPush);
console.log('Socket Reconnect...');
if (Socket.readyState !== 3) {
Socket = null;
createSocket();
}
}
const awaitMessageSend = msg => {
setTimeout(() => {
Socket.readyState === 0 ? awaitMessageSend(msg) : Socket.send(anyToString(msg));
})
}
const SocketOnClose = () => {
clearInterval(timingSocketPush);
console.log('SocketDisconnect,Reconnect...');
if (Socket.readyState !== 2) {
Socket = null;
createSocket();
}
}
export const sendPing = (duration = 10000, str = 'ping') => {
clearInterval(timingSocketPush);
Socket.send(anyToString(str));
timingSocketPush = setInterval(() => {
Socket.send(str);
}, duration);
}
export const pushMessage = msg => {
if(typeOf msg !== 'string')
return;
if (Socket !== null && Socket.readyState === 3) {
Socket.close();
createSocket();
} else if (Socket.readyState === 1)
Socket.send(msg);
else if (Socket.readyState === 0)
awaitMessageSend(msg);
}
|