Cocos WebSocket 工具类

/**
 * WebSocket工厂类
 * @cn 提供两个创建实例的方法:一个是创建单例模式;另一个是创建多个实例。用于创建WebSocket连接。
 * 提供原生的回调函数 onopen、onmessage、onclose、onerror
 */
export default class WebSocketFactory {

    // private  onopen: (event: Event) => void;
    // private sendMsg: (msg: any) => void;
    // private  onmessage: (event: MessageEvent) => void;
    // private  onclose: (event: CloseEvent) => void;
    // private  onerror: (event: Event) => void;



    // 原生的WebSocket单例
    public static wsSiglletonInstance: WebSocket;
    public static url: string;


    /**
     * 重连
     * @param webSocket WebSocket实例
     * @param url 服务器地址
     * @returns  WebSocket 连接
     */
    public static retryConnect(webSocket: WebSocket, url: string):WebSocket  {
        webSocket.close();
        webSocket = new WebSocket(url);
       
        this.onopenning(webSocket, (event) => {
            console.log('WebSocket 连接已打开');
        })
        return webSocket;
    }



    /**
     * 获取WebSocket单例
     * @param url 服务器地址
     * @returns  WebSocket单例
     */
    public static getWebSocketSingleton(url): WebSocket {
        this.url = url;
        if (!WebSocketFactory.wsSiglletonInstance) {
            WebSocketFactory.wsSiglletonInstance = new WebSocket(this.url);
        }
        return WebSocketFactory.wsSiglletonInstance;
    }

    public static onopenning(webSocket: WebSocket, onopen: (event: Event) => void): WebSocketFactory {
        webSocket.onopen = onopen;
        return this;
    }

    /**
     * 保持开启状态下发送消息
     * @cn 发送消息
     * @param webSocket WebSocket实例
     * @param msg 消息
     */
    public static openningSendMsg(webSocket: WebSocket, msg: any): WebSocketFactory {

        if (webSocket.readyState === WebSocket.OPEN) {
            webSocket.send(JSON.stringify(msg));
        } else {
        
            this.onopenning(webSocket, (event) => {
                console.log('WebSocket 连接已打开');
                webSocket.send(JSON.stringify(msg));
            })
        }
        return this;

    }


    /**
     * 获取WebSocket实例
     * @param url 服务器地址
     * @returns  WebSocket实例
     */

    public static getWebSocketNew(url): WebSocket {
        return new WebSocket(url);
    }


}

你可能感兴趣的:(websocket,网络协议,网络)