最近公司要用websocket 搞一个大屏可视化,找了许多案例才弄明白
import {
getToken } from '@/utils/auth'
export default class SocketServer {
// 定义单例(单个实例)模式
static instance = null
static get Instance() {
if (!SocketServer.instance) {
//防止创建多个实例对象
SocketServer.instance = new SocketServer()
}
return SocketServer.instance
}
// 和服务端连接的socket对象
ws = null
// 存储回调函数
callBackMapping = {
}
// 标识是否连接成功
connection = false
// 记录重试的次数
sendRetryCount = 0;
// 重新连接尝试的次数
connectRetryCount = 0;
// 定义连接服务器的方法
connect() {
// 连接服务器
if (!window.WebSocket) {
return console.log('您的浏览器不支持WebSocket') }
this.ws = new WebSocket("ws:/