WsM.ts 1.6 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263
  1. import { TipsLayer } from "../../prefab/layer/TipsLayer";
  2. import { Tips } from "../mgr/Tips";
  3. import { WS, WsRequest, WsResponse } from "../net/WS";
  4. export default class WsM {
  5. private static _ins: WsM;
  6. public static get ins(): WsM {
  7. return (WsM._ins ??= new WsM());
  8. }
  9. private _lastShowTimeoutDialogTime: number = 0;
  10. public async syncRequest(
  11. protocolId: number,
  12. data: any,
  13. timeout: number = 5000
  14. ): Promise<any> {
  15. return new Promise((resolve, reject) => {
  16. let getData = false;
  17. let cb = (msg: WsResponse) => {
  18. getData = true;
  19. console.log("websocket msg", msg);
  20. WS.ins.off(protocolId, cb, cb);
  21. if (msg.success == true) {
  22. if (msg.data) {
  23. resolve(msg.data);
  24. } else {
  25. resolve({});
  26. }
  27. } else {
  28. console.error(msg);
  29. Tips.show(msg.msg);
  30. resolve(null);
  31. }
  32. };
  33. WS.ins.on(protocolId, cb, cb);
  34. WsRequest.create(protocolId).setData(data).send();
  35. setTimeout(() => {
  36. // WS.ins.off(protocolId, cb, cb);
  37. // reject("timeout");
  38. if (getData) {
  39. return;
  40. }
  41. console.error("timeout", protocolId);
  42. WS.ins.onTimeout();
  43. if (Date.now() - this._lastShowTimeoutDialogTime > 10000) {
  44. this._lastShowTimeoutDialogTime = Date.now();
  45. } else {
  46. return;
  47. }
  48. TipsLayer.forceConfirm("Hello", "Welcome back!").then((success) => {
  49. if (success) {
  50. window.location.reload();
  51. }
  52. });
  53. }, timeout);
  54. });
  55. }
  56. }