cocos-creator连接服务端 注册与登入

cc.Class({
    extends: cc.Component,

    properties: {
              //外部传入account输入款
            account:cc.EditBox,
             //外部传入password输入款
            password:cc.EditBox,
            tips:cc.Node,
            labyer:cc.Label,
    },

    onLoad () {},

    start () {
            this.ws=null;
            this.conect();
    },

    conect:function()
    {
       this.ws = new WebSocket("ws://192.168.0.118:8000/login");
        //写好的服务端,根据不同的返回值,输出对应的提示
       this.ws.onopen = function (event) {
            console.log("Send Text WS was opened.");
        }.bind(this);
        this.ws.onmessage = function (event) {
            switch(JSON.parse(event.data).cmd)
            {
                case 2:
                this.tips.active=true;
                this.labyer.string='注册失败';
                break;
                case 3:
                this.tips.active=true;
                this.labyer.string='登入失败';
                break;
                case 4:
                this.tips.active=true;
                this.labyer.string='注册成功';
                break;
                case 5:
                this.tips.active=true;
                this.labyer.string='登入成功';
                break;
                default:
                this.tips.active=true;
                this.labyer.string=JSON.parse(event.data).msg;
                cc.log('JSON.parse(event.data).cmd='+JSON.parse(event.data).cmd);
                break;
            }
        }.bind(this);
        this.ws.onerror = function (event) {
            console.log("Send Text fired an error");
        }.bind(this);
        this.ws.onclose = function (event) {
            console.log("WebSocket instance closed.");
        }.bind(this);
       
        // setTimeout(function () {
        //     if ( this.ws.readyState === WebSocket.OPEN) {
        //         this.ws.send("Hello WebSocket, 我发账号啦:995455665");12
        //     }
        //     else {
        //         console.log("WebSocket instance wasn't ready...");
        //     }
        // }.bind(this), 3000);
    },

    //注册
    Register:function()
    {
        //两个文本输入框内容
        var user={account:this.account.string,password:this.password.string};
        //JSON.stringify()函数是Json转字符串
        var str=JSON.stringify(user);

        //数据需要与服务端枚举类型匹配
        var pack={cmd:0,msg:str};

        var packstr=JSON.stringify(pack);

        this.ws.send(packstr)

       
    },

    //登入
    Loading:function()
    {
        var user={account:this.account.string,password:this.password.string};

        var str=JSON.stringify(user);

        var pack={cmd:1,msg:str};

        var load=JSON.stringify(pack);

        this.ws.send(load);
    },

    isFalse()
    {




    },

    isHide()
    {
        this.tips.active=false;
    }

    // update (dt) {},
});

猜你喜欢

转载自blog.csdn.net/piyixia/article/details/89247484