// websocket.js 导出的自己封装的websocket模块

export default class websocket{
    public static sock: WebSocket | null; // 连接的socket 对象 WebSocket, h5标准对象;
    public static addr: string;
    public static port: number;
    public static isinit: boolean = false;

    // 构造函数
    public static init(addr: string, port: number){
        if(websocket.isinit)
            return;
        websocket.addr = addr;
        websocket.port = port;
    }
    // 网络连接成功了以后调用
    public static on_open(event:any) {
        // test
        console.log('网络连接成功!');
        // end
        // 开启心跳包
        websocket.heart_pack();
    }
    // 心跳包
    public static heart_pack(){
        websocket.send_data("1");
        if(websocket.sock != null)
            setTimeout(websocket.heart_pack, 10000);
    }

    // 客户端收到数据的时候
    public static on_message(event:any) {
        console.log("收到数据...", event.data);
    }

    // 客户端收到socket 关闭的时间的时候调用;
    public static on_close (event:any) {
        websocket.close();
    }

    public static on_error (event:any) {
        websocket.close();
    }

    public static close() {
        if (websocket.sock != null) {
            console.log('关闭连接...');
            websocket.sock.close(); // 关闭socket
            websocket.sock = null;
        }
    }

    // 连接函数,
    public static connect() {
        websocket.sock = new WebSocket('ws://' + websocket.addr+':'+websocket.port+'/ws'); // h5标准的websocket对象
        websocket.sock.binaryType = "arraybuffer"; // 配置接受二进制的数据类型,与服务器保持一次, "Blob"

        // 为这个websocket对象制定对应的回掉函数;
        websocket.sock.onopen = websocket.on_open;
        websocket.sock.onmessage = websocket.on_message;
        websocket.sock.onclose = websocket.on_close;
        websocket.sock.onerror = websocket.on_error;
    }

    // 发送数据, sock.send;
    public static send_data(data:any) {
        if(websocket.sock != null){
            websocket.sock.send(data);
        }
    }
};