Forráskód Böngészése

登錄websocket轉同步

zane 1 hónapja
szülő
commit
f5cf35d097

+ 61 - 19
assets/resources/scripts/Loading.ts

@@ -1,12 +1,14 @@
 import { _decorator, Component, Node } from "cc";
 import PogHttp, { PogLoginResp } from "./net/PogHttp";
-import { WalletListener, WalletManager } from "./web3/WalletManager";
+import { WalletManager } from "./web3/WalletManager";
 import { director } from "cc";
 import BaseUI from "./base/BaseUI";
 import { WS } from "./net/WS";
 import { ProgressBar } from "cc";
-import TgM from "./mgr/TgM";
 import LoginM from "./mgr/LoginM";
+import AB from "./base/AB";
+import ConfigM from "./mgr/ConfigM";
+import WsM from "./mgr/WsM";
 const { ccclass, property } = _decorator;
 
 @ccclass("Loading")
@@ -21,9 +23,13 @@ export class Loading extends BaseUI {
     this.login();
   }
 
+  private _enabled: boolean = true;
+
   public async U(text: string, progress: number) {
-    await this.setText("lbl_progress_info", text);
-    let fromProgress = this.progressBar.progress;
+    const progressBar = Loading.ins.progressBar;
+
+    await Loading.ins.setText("lbl_progress_info", text);
+    let fromProgress = progressBar.progress;
     let toProgress = progress;
 
     if (fromProgress >= toProgress) {
@@ -33,17 +39,21 @@ export class Loading extends BaseUI {
     let duration = Math.random() * 0.5 + 0.01;
     let elapsed = 0;
     let deltaTime = 0.01;
-    while (elapsed < duration) {
+    while (elapsed < duration && this._enabled) {
       elapsed += deltaTime;
       let t = elapsed / duration;
       let progress = fromProgress + (toProgress - fromProgress) * t;
-      this.progressBar.progress = progress;
+      if (!progressBar) {
+        console.warn("progressBar is null", text, progress);
+        return;
+      }
+      progressBar.progress = progress;
       let pp = progress * 100;
       if (pp > 100) {
         pp = 100;
       }
       pp = Math.floor(pp);
-      await this.setText("lbl_progress_value", pp + "%");
+      await Loading.ins.setText("lbl_progress_value", pp + "%");
       await new Promise((resolve) => setTimeout(resolve, 10));
     }
   }
@@ -65,6 +75,7 @@ export class Loading extends BaseUI {
   }
 
   protected onDestroy(): void {
+    this._enabled = false;
     Loading._ins = null;
   }
   async login() {
@@ -87,6 +98,7 @@ export class Loading extends BaseUI {
 
     let result = await LoginM.ins.login();
     console.warn("result", result);
+
     if (result) {
       await this.onLoginSuccess(result);
     } else {
@@ -96,21 +108,51 @@ export class Loading extends BaseUI {
 
   async onLoginSuccess(res: PogLoginResp) {
     let self = this;
-    if (res) {
-      await self.U("Logging Success...", 1);
-      await new Promise((resolve) => setTimeout(resolve, 100));
-      await self.U("Entering hall...", 1);
-      await new Promise((resolve) => setTimeout(resolve, 100));
+    if (!res) {
+      await this.loginFailed();
+      self.FindNode("btn_retry").active = true;
+      return;
+    }
 
-      director.loadScene("hall");
+    await self.U("Logging Success...", 0.7);
+    await new Promise((resolve) => setTimeout(resolve, 10));
 
-      let url =
-        "ws2://albtestkuma-1290122235.ap-southeast-1.elb.amazonaws.com/pog";
-      await WS.ins.connect(url, res.token);
-    } else {
-      await self.U("Login failed...", 1);
-      self.FindNode("btn_retry").active = true;
+    let config = await ConfigM.ins.loadConfig();
+
+    if (!config) {
+      self.U("Loading config failed...", 1);
+      await this.loginFailed();
+      return;
+    }
+
+    self.U("Loading config success...", 0.7);
+    await new Promise((resolve) => setTimeout(resolve, 30));
+
+    self.U("Loading Assets ...", 0.8);
+    let ab = await AB.ins.loadInLoading();
+    await new Promise((resolve) => setTimeout(resolve, 10));
+    self.U("Loading Assets success...", 0.8);
+
+    let connectResult = await WS.ins.connect(res.wsUrl, res.token);
+    if (!connectResult) {
+      this.U("Connect websocket failed...", 1);
+      await this.loginFailed();
+      return;
     }
+
+    await new Promise((resolve) => setTimeout(resolve, 300));
+
+    await self.U("Get user info...", 0.8);
+    let userInfo = await WsM.ins.userInfo();
+    if (!userInfo) {
+      this.U("Get user info failed...", 1);
+      await this.loginFailed();
+      return;
+    }
+    await self.U("Entering hall...", 1);
+    await new Promise((resolve) => setTimeout(resolve, 30));
+
+    director.loadScene("hall");
   }
 
   showLoading(arg0: boolean) {}

+ 6 - 1
assets/resources/scripts/base/AB.ts

@@ -3,7 +3,12 @@ import { SpriteFrame } from "cc";
 import { Prefab, resources } from "cc";
 
 export default class AB {
-  loadRes (path: string, asset: typeof Asset): Promise<Asset> {
+  async loadInLoading(): Promise<boolean> {
+    return new Promise((resolve, reject) => {
+      resolve(true);
+    });
+  }
+  loadRes(path: string, asset: typeof Asset): Promise<Asset> {
     return new Promise((resolve, reject) => {
       resources.load(path, asset, (err, asset) => {
         if (err) {

+ 26 - 0
assets/resources/scripts/mgr/ConfigM.ts

@@ -0,0 +1,26 @@
+import PogHttp, { Config } from "../net/PogHttp";
+
+
+ 
+
+export default class ConfigM {
+  private static _ins: ConfigM;
+  public static get ins(): ConfigM {
+    return ConfigM._ins || new ConfigM();
+  }
+
+  private _config: Config;
+
+    public async loadConfig(): Promise<boolean> {
+      
+
+
+    let config = await PogHttp.ins.allConfig();
+    console.warn("config", config);
+    if (!config) {
+      return false;
+    }
+    this._config = config;
+    return true;
+  }
+}

+ 9 - 0
assets/resources/scripts/mgr/ConfigM.ts.meta

@@ -0,0 +1,9 @@
+{
+  "ver": "4.0.24",
+  "importer": "typescript",
+  "imported": true,
+  "uuid": "a1fdb16e-7a47-45b2-8ec1-caa5aa729465",
+  "files": [],
+  "subMetas": {},
+  "userData": {}
+}

+ 4 - 4
assets/resources/scripts/mgr/LoginM.ts

@@ -11,7 +11,7 @@ export default class LoginM {
 
   async login(): Promise<PogLoginResp | null> {
     if (await TgM.ins.isTG()) {
-      await Loading.ins.U("Telegram Login...", 1);
+      await Loading.ins.U("Telegram Login...", 0.3);
       return await TgM.ins.login();
     }
 
@@ -30,9 +30,9 @@ export default class LoginM {
     await Loading.ins.U("Connecting to wallet...", 0.3);
     let walletListener: WalletListener = {
       onLoginSuccess: async (account: string, balance: number) => {
-        await Loading.ins.U("Wallet connected...", 0.6);
-        await new Promise((resolve) => setTimeout(resolve, 200));
-        await Loading.ins.U("Logging in...", 0.9);
+        await Loading.ins.U("Wallet connected...", 0.4);
+        await new Promise((resolve) => setTimeout(resolve, 30));
+        await Loading.ins.U("Logging in...", 0.5);
         PogHttp.ins
           .loginByWalletAddress(account)
           .then(async (res: PogLoginResp) => {

+ 40 - 0
assets/resources/scripts/mgr/WsM.ts

@@ -0,0 +1,40 @@
+import { WS, WsRequest, WsResponse } from "../net/WS";
+
+export default class WsM {
+  private static _ins: WsM;
+  public static get ins(): WsM {
+    return WsM._ins || new WsM();
+  }
+
+  public async userInfo(): Promise<any> {
+    let result = await this.syncRequest(20001, {});
+    console.log("userInfo", result);
+    return result;
+  }
+
+  public async syncRequest(protocolId: number, data: any): Promise<any> {
+    return new Promise((resolve, reject) => {
+      resolve({});
+      return;
+
+      let cb = (msg: WsResponse) => {
+        WS.ins.off(protocolId, cb, cb);
+        if (msg.success) {
+          resolve(msg.data);
+        }
+        reject(msg.msg);
+      };
+      WS.ins.on(protocolId, cb, cb);
+      WsRequest.create(protocolId).setData(data).send();
+
+      setTimeout(() => {
+        WS.ins.off(protocolId, cb, cb);
+
+        // let resp = new WsResponse();
+        // resp.success = false;
+        // resp.msg = "timeout";
+        resolve(null);
+      }, 5000);
+    });
+  }
+}

+ 9 - 0
assets/resources/scripts/mgr/WsM.ts.meta

@@ -0,0 +1,9 @@
+{
+  "ver": "4.0.24",
+  "importer": "typescript",
+  "imported": true,
+  "uuid": "94f18a17-e38b-498d-8ec3-c3239f826a1e",
+  "files": [],
+  "subMetas": {},
+  "userData": {}
+}

+ 58 - 0
assets/resources/scripts/net/PogHttp.ts

@@ -15,6 +15,58 @@ export interface PogLoginResp {
   wsUrl: string;
 }
 
+export class ConfigGood {
+  id: number;
+  name: string;
+  desc: string;
+  type: number;
+  param1: any;
+  param2: any;
+  param3: any;
+  param4: any;
+}
+
+export class ConfigShopItem {
+  id: number;
+  goodId: number;
+  num: number;
+  storeId: number;
+  usdPrice: number;
+  diamondPrice: number;
+  adPrice: number;
+  total: number;
+  dailyUserLimit: number;
+  userLimit: number;
+  userAdLimit: number;
+  dailyUserAdLimit: number;
+  sort: number;
+  expireTime: number | null;
+}
+export class ConfigStore {
+  id: number;
+  name: string;
+  shopList: ConfigShopItem[];
+}
+
+export class ConfigRecharge {
+  id: number;
+  usd: number;
+  diamonds: number;
+  extraDiamonds: number;
+  tgStars: number;
+  goodList: number[];
+  numList: number[];
+  bonusList: number[];
+  bonusNumList: number[];
+  firstRechargeList: number[];
+  firstRechargeNumList: number[];
+}
+export class Config {
+  goodList: ConfigGood[];
+  storeList: ConfigStore[];
+  rechargeList: ConfigRecharge[];
+}
+
 export default class PogHttp {
   getPogBoosterList() {
     let a = [];
@@ -71,4 +123,10 @@ export default class PogHttp {
     });
     return res;
   }
+
+  async allConfig(): Promise<Config> {
+    const path = "/pog-service/login/config";
+    const res = await this._apiRequest(path, {});
+    return res;
+  }
 }

+ 12 - 8
assets/resources/scripts/net/PogWebsocket.ts

@@ -9,6 +9,10 @@ export class PogWebsocket {
     return pogWebsocket;
   }
 
+  public get connected(): boolean {
+    return this._connected;
+  }
+
   ping() {
     if (!this._connected) {
       return;
@@ -39,12 +43,12 @@ export class PogWebsocket {
   private onOpen() {
     console.log("onOpen");
     this._connected = true;
-    this._ws.send(
-      JSON.stringify({
-        type: "test",
-        data: "test",
-      })
-    );
+    // this._ws.send(
+    //   JSON.stringify({
+    //     type: "test",
+    //     data: "test",
+    //   })
+    // );
   }
 
   private onMessage(data: MessageEvent) {
@@ -64,11 +68,11 @@ export class PogWebsocket {
     this._connected = false;
   }
 
-  public send(data: any) {
+  public async send(data: any) {
     if (!this._connected) {
       return;
     }
-    this._ws.send(data);
+    await this._ws.send(data);
   }
 
   public close() {

+ 54 - 8
assets/resources/scripts/net/WS.ts

@@ -6,13 +6,49 @@ import {
 } from "./PogWebsocket";
 const { ccclass, property } = _decorator;
 
+export class WsResponse {
+  protocolId: number;
+  requestId: number;
+  code: number;
+  success: boolean;
+  data: any;
+  msg: string;
+}
+
+export class WsRequest {
+  requestId: number;
+  protocolId: number;
+  data: any;
+  public static create(protocolId: number): WsRequest {
+    let msg = new WsRequest();
+    msg.protocolId = protocolId;
+    msg.requestId = Math.floor(Math.random() * 1000000);
+    msg.requestId = 2;
+    return msg;
+  }
+
+  public setData(data: any): WsRequest {
+    this.data = data;
+    return this;
+  }
+
+  public async send() {
+    let data = JSON.stringify(this);
+    await WS.ins.send(data);
+  }
+}
+
 @ccclass("WS")
 export class WS extends Component implements IWebsocketMessage {
   OnMessage(data: any): void {
+    console.error("onMessage", data);
+
     if ("pong" == data) {
       return;
     }
-    console.log("onMessage", data);
+
+    let msg: WsResponse = JSON.parse(data);
+    this._e.emit("" + msg.protocolId, msg);
   }
   init() {}
 
@@ -23,7 +59,7 @@ export class WS extends Component implements IWebsocketMessage {
         this.pogWebsocket = PogWebsocket.create(full_url, this);
         resolve(true);
       } catch (e) {
-        console.error(e)
+        console.error(e);
         resolve(false);
       }
     });
@@ -47,8 +83,14 @@ export class WS extends Component implements IWebsocketMessage {
     }
   }
 
-  public send(data: any) {
-    this.pogWebsocket.send(data);
+  public async send(msg: any) {
+    console.log("send", msg);
+    for (let i = 0; i < 3; i++) {
+      if (!this.pogWebsocket.connected) {
+        await new Promise((resolve) => setTimeout(resolve, 500));
+      }
+    }
+    return await this.pogWebsocket.send(msg);
   }
 
   public close() {
@@ -64,16 +106,20 @@ export class WS extends Component implements IWebsocketMessage {
     director.addPersistRootNode(this.node);
   }
 
-  public on(eventName: string, handler: (...args: any[]) => void, target: any) {
-    this._e.on(eventName, handler, target);
+  public on(
+    protocolId: number,
+    handler: (...args: any[]) => void,
+    target: any
+  ) {
+    this._e.on("" + protocolId, handler, target);
   }
 
   public off(
-    eventName: string,
+    protocolId: number,
     handler: (...args: any[]) => void,
     target: any
   ) {
-    this._e.off(eventName, handler, target);
+    this._e.off("" + protocolId, handler, target);
   }
 
   protected onDestroy(): void {