cocos creator中websocket單例模式正確姿式(不用掛到Scene上,直接getInstance就行)

let websocket = cc.Class({
    extends: cc.Component,

    properties: {
        _sock: null,
        _services_handler: null,
        _msg_queue: [],

        is_lock: false,
    },

    onLoad: function () {
        console.log("websocket onLoad");
    },

    onDestroy: function () {
        console.log("websocket onDestroy");
    },

    lock: function () {
        this.is_lock = true;
    },

    unlock: function () {
        this.is_lock = false;
    },

    update: function () {
        if (this.is_lock) {
            return;
        }

        if (this._msg_queue.length > 0) {
            // 從消息隊列中取得一個消息
            let obj_data = this._msg_queue.shift();

            let ctype = obj_data.ctype;
            let body = obj_data.body;

            // 有錯誤
            if (body.errormsg) {
                console.error("[", ctype, "]", body);
                return;
            }
            console.log("[", ctype, "]", body);


            if (this._services_handler[ctype]) {
                this._services_handler[ctype](ctype, body);
            } else {
                console.warn(ctype, "客戶端沒有註冊!!!");
            }
        }
    },

    on_open: function () {
        console.log("鏈接服務器成功!!!");
    },

    on_message: function (event) {
        if (!this._services_handler) {
            return;
        }

        let obj_data = JSON.parse(event.data);
        this._msg_queue.push(obj_data);
    },

    on_close: function () {
        console.log("on_close!!!");
        this.close();
    },

    // 好比沒有連上
    on_error: function () {
        console.log("on_error!!!");
        this.close();
    },

    close: function () {
        if (this._sock) {
            this._sock.close();
            this._sock = null;
        }
    },

    connect: function (url) {
        this._sock = new WebSocket(url);

        this._sock.binaryType = "arraybuffer";

        this._sock.onopen = this.on_open.bind(this);
        this._sock.onmessage = this.on_message.bind(this);
        this._sock.onclose = this.on_close.bind(this);
        this._sock.onerror = this.on_error.bind(this);
    },

    send_data: function (obj_data) {
        if (!this._sock || this._sock.readyState != WebSocket.OPEN) {
            console.error("還沒有鏈接服務器!!!");
            return;
        }
        let json_data = JSON.stringify(obj_data);
        this._sock.send(json_data);
    },

    register_services_handler: function (services_handler) {
        this._services_handler = services_handler;
    },

    remove_services_handler: function () {
        this._services_handler = null;
    }
});

websocket._instance = null;
websocket.getInstance = function () {
    if (!websocket._instance) {
        let node = new cc.Node();
        websocket._instance = node.addComponent(websocket);
        cc.game.addPersistRootNode(node);
    }

    return websocket._instance;
};

module.exports = websocket;
相關文章
相關標籤/搜索