1. 引用 reconnecting-websocket.js
npm i reconnecting-websocket
2. 建立websocket.ts
import ReconnectingWebSocket from 'reconnecting-websocket';
let rws: any = null;
let globalCallback: any = null;
//初始化websocket
const initWebsocket = () => {
// let url = "ws://192.168.3.87:8081/ws";
let url = "ws://localhost:3001";
// 建立websocket 连接
rws = new ReconnectingWebSocket(url);
rws.addEventListener("open", () => {
if (!rws) return;
if (rws.readyState === 1) {
webSocketOpen();
}
});
//收信
rws.addEventListener("message", (e: any) => {
webSocketOnMessage(e.data);
});
// 错误时进行的处理
rws.addEventListener("error", (e: any) => {
console.error(e.message);
});
// 关闭时进行的操作
rws.addEventListener("close", () => {
webSocketClose();
});
}
//连接socket建立时触发
const webSocketOpen = () => {
console.log("建立成功,发送消息");
let token: any = localStorage.getItem('tokenkey');
if (!isNullOrUndefined(token)) {
let obj = {
kind: 1,
token: token,
id: 0
}
sendSock(obj, () => { });
}
}
//客户端接收服务端数据时触发,e为接受的数据对象
const webSocketOnMessage = (data: any) => {
globalCallback(data);//JSON.parse(decrypt(data))
}
//发送数据
const webSocketSend = (data: object) => {
rws.send(data);
}
//关闭socket
const webSocketClose = () => {
rws.close();
console.log("对话连接已关闭");
}
// 实际调用的方法
const sendSock = (agentData: any, callback: any) => {
console.log("重新连接")
globalCallback = callback;
console.log("rws.readyState", rws);
switch (rws.readyState) {
//OPEN:值为1,表示连接成功,可以通信了。
case rws.OPEN:
console.log("OPEN")
webSocketSend(agentData);
break;
// CONNECTING:值为0,表示正在连接。
case rws.CONNECTING:
console.log("CONNECTING", callback)
setTimeout(function () {
//@ts-ignore
webSocketSend(agentData, callback);
}, 1000);
break;
// CLOSING:值为2,表示连接正在关闭。
case rws.CLOSING:
console.log("CLOSING")
setTimeout(() => {
//@ts-ignore
webSocketSend(agentData, callback);
}, 1000);
break;
// CLOSED:值为3,表示连接已经关闭,或者打开连接失败。
case rws.CLOSED:
console.log("CLOSED")
// do something
break;
default:
console.log("default")
break;
}
}
export { initWebsocket, webSocketClose, sendSock };
3. 页面使用
import * as socketApi from '@/utils/websocket'
socketApi.sendSock('发送的数据', (e: any) => {
console.log("后台发送过来的数据", e)
})