Cocos 网络资源管理器

网络资源管理器

实现:

(()=>{
    window.g_Net = new class CNet{
        constructor(){
            this.LoginUrl = "服务器地址:端口";
            this.app = null;
            this._uid = 0;
        }

        set uid(val){
            this._uid = val;
        }

        get uid(){
            return this._uid;
        }

        disConnect(){
            if(this.app){
                this.app.close();
            }
            this.app = null;
        }
		//入口函数,启动网络连接
        doConnect(url){
            this.app = new WebSocket(url);

            this.app.onopen = () => {}
            

            this.app.onmessage = (event) => {
                this.onMessage(JSON.parse(event.data));
            }

            this.app.onclose = () => { }
        }
		//使用信号槽转发数据
        onMessage(data){
            cc.log("已接受,发送信号");
            g_slot.emit(g_Event, data);
        }
		//C2S发包
        send(data) {
            if (this.app) {
                this.app.send(JSON.stringify(data));
            }
        }

        httpRequest(url, data, cb, isParse = true) {  //第四个参数的返回值为true
            let xhr = cc.loader.getXMLHttpRequest();//得到一个XMLHttpRequest实例。
            if (!data) {//请求时没有数据
                xhr.open("GET", url);
            } else {
                xhr.open("GET", url + "?data=" + JSON.stringify(data));
            }
            // xhr.onreadystatechange 是当连接状态改变的时候会调用
            xhr.onreadystatechange = () => {//听
                if (xhr.readyState == 4) {
                    if (xhr.status == 200) {
                        if (isParse) {
                            cb(JSON.parse(xhr.responseText));
                        } else {
                            cb(xhr.responseText);
                        }
                    } else {
                        // 重发
                    }
                }
            }
            xhr.send();
        }
    }

})()

网络资源管理器知识点:

全局同一由这个脚本进行与服务器交互,功能集中方便使用,并且可以保存个别数据存在全局。

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值