function WebSocketWithHeartbeat(url) {
    this.url = url;
    this.websocket = null;
    this.heartbeatInterval = 3000; // 心跳间隔时间（毫秒）
    this.reconnectInterval = 1000; // 重新连接间隔时间（毫秒）
    this.heartbeatTimer = null;

    this.onOpen = null; // 连接打开时的回调函数
    this.onMessage = null; // 收到消息时的回调函数
    this.onClose = null; // 连接关闭时的回调函数
    this.onError = null; // 发生错误时的回调函数

    this.connect();
}

WebSocketWithHeartbeat.prototype.connect = function() {
    this.websocket = new WebSocket(this.url);

    this.websocket.onopen = () => {
        console.log('WebSocket 连接已打开');

        if (typeof this.onOpen === 'function') {
            this.onOpen();
        }

        this.startHeartbeat();
    };

    this.websocket.onmessage = (event) => {
        console.log('收到消息：', event.data);

        if (typeof this.onMessage === 'function') {
            this.onMessage(event.data);
        }
    };

    this.websocket.onclose = (event) => {
        console.log('WebSocket 连接已关闭');

        if (typeof this.onClose === 'function') {
            this.onClose();
        }

        this.stopHeartbeat();

        setTimeout(() => {
            this.connect();
        }, this.reconnectInterval);
    };

    this.websocket.onerror = (error) => {
        console.error('WebSocket 错误：', error);

        if (typeof this.onError === 'function') {
            this.onError(error);
        }
    };
};

WebSocketWithHeartbeat.prototype.startHeartbeat = function() {
    this.stopHeartbeat(); // 先停止之前的心跳计时器

    this.heartbeatTimer = setInterval(() => {
        this.sendHeartbeat();
    }, this.heartbeatInterval);
};

WebSocketWithHeartbeat.prototype.stopHeartbeat = function() {
    if (this.heartbeatTimer) {
        clearInterval(this.heartbeatTimer);
        this.heartbeatTimer = null;
    }
};

WebSocketWithHeartbeat.prototype.sendHeartbeat = function() {
    var heartbeatMessage = "{code:200,msg:1111,data:null}"

    if (this.websocket.readyState === WebSocket.OPEN) {
        // this.websocket.send(heartbeatMessage);
    }
};

WebSocketWithHeartbeat.prototype.send = function(message) {
    if (this.websocket.readyState === WebSocket.OPEN) {
        this.websocket.send(message);
    } else {
        console.error('WebSocket 连接未打开');
    }
};

WebSocketWithHeartbeat.prototype.close = function() {
    if (this.websocket) {
        this.websocket.close();
    }
};

// 示例用法
const socket = new WebSocketWithHeartbeat('ws://127.0.0.1:16006/ws');

socket.onOpen = function() {
    console.log('连接已打开');
    // 可以在这里执行一些初始化操作或发送初始消息
};

// socket.onMessage = function(data) {
//     console.log('收到消息：', data);
//     // 处理接收到的消息
// };

socket.onClose = function() {
    console.log('连接已关闭');
};

socket.onError = function(error) {
    console.error('WebSocket 错误：', error);
};

// 发送消息
socket.send('Hello, WebSocket!');