[前端]Typescript单例模式实现websocket通信
class SocketService {
static instance: any = null;
static get Instance() {
if (SocketService.instance) {
return SocketService.instance;
}
return (SocketService.instance = new SocketService());
}
ws: any = null;
callBackMapping = {};
connected = false;
sendRetryCount = 0;
connectRetryCount = 0;
sendFixHeart() {
let sendFixHeartTimer: any = null;
clearInterval(sendFixHeartTimer);
sendFixHeartTimer = setInterval(() => {
this.ws.send(JSON.stringify({}));
}, 20000);
}
connect() {
if (!window.WebSocket) {
return console.log('您的浏览器不支持WebSocket');
}
this.ws = new WebSocket('这里放地址');
this.ws.onopen = () => {
console.log('连接服务端成功了,ws状态是' + this.ws.readyState);
this.connected = true;
this.connectRetryCount = 0;
this.sendFixHeart();
};
this.ws.onclose = () => {
if (this.connectRetryCount >= 10) {
this.ws.close();
console.log('重新连接服务器失败');
} else {
this.connected = false;
this.connectRetryCount++;
setTimeout(() => {
this.close();
this.connect();
console.log('连接服务端失败第' + this.connectRetryCount + '次,1秒后重试');
}, 1000);
}
};
this.ws.onerror = function () {
console.log('Error,websocket连接错误');
};
}
send(data: any) {
if (this.connected) {
this.sendRetryCount = 0;
this.ws.send(JSON.stringify(data));
} else {
this.sendRetryCount++;
setTimeout(() => {
this.send(data);
console.log('已经重新发送第:' + this.sendRetryCount + '次');
}, 1000);
}
}
close() {
this.ws.close();
}
}
export default SocketService;
<script setup lang="ts">
import { reactive } from 'vue';
import SocketService from '../utils/websocket';
const data = reactive({
socketServe: SocketService.Instance
});
const socket: any = data.socketServe;
/**
* 发送请求
*/
function send() {
socket.send({
data: { option: 'listen', id: idInt }
});
}
setTimeout(() => {
send();
}, 100);
/**
* 发送数据
*/
socket.connect();
/**
* 接受信息
*/
socket.ws.onmessage = (msg: { data: any }) => {
const msgview = JSON.parse(msg.data);
return msgview
};
</script>
|