SocketClient.ts 2.4 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889
  1. import { _decorator, Component, assetManager, game } from "cc"
  2. import { GameCtr } from "../gameCtr"
  3. import { processCtr } from "./processCtr"
  4. const { ccclass, property } = _decorator
  5. @ccclass("SocketClient")
  6. export class SocketClient extends Component {
  7. @property({ type: processCtr })
  8. public processCtr: processCtr | null = null
  9. private roomId: number = 1
  10. public gameId: number = 8
  11. private SERVER_URL: String = `wss://${location.hostname === 'localhost' ? 'airpg1.izouma.com' :location.hostname}`
  12. public socket:any ;
  13. // 你可以定义其他属性或者私有变量来存储游戏状态或与UI交互的节点
  14. onLoad() {
  15. // 加载 socket.io 脚本
  16. // this.scheduleOnce(() => { this.initSocketConnection() }, 10)
  17. }
  18. public initSocketConnection() {
  19. this.socket = io(this.SERVER_URL)
  20. this.socket.on("connect", () => {
  21. console.log("Connected to the server.")
  22. })
  23. this.socket.on(`${this.gameId}`, (data) => {
  24. console.log('接收到消息:'+data.type)
  25. if (typeof data === "string") {
  26. try {
  27. data = JSON.parse(data)
  28. } catch (e) {
  29. console.error("Failed to parse message:", data)
  30. return
  31. }
  32. }
  33. if (data && data.type) {
  34. console.log('加入处理队列:'+data.type)
  35. this.processCtr.messageQueue.push(data) // Push the message to the queue
  36. this.processCtr.processNextMessage() // Attempt to process the next message
  37. }
  38. })
  39. }
  40. }
  41. // private SERVER_URL:string = "wss://airpg.izouma.com/";
  42. // // 指令处理函数映射
  43. // private commandHandlers: { [key: string]: (data: any) => void } = {
  44. // 'command1': this.handleCommand1,
  45. // 'command2': this.handleCommand2,
  46. // // ... 其他指令处理函数
  47. // };
  48. // onLoad() {
  49. // this._socket = new WebSocket(this.SERVER_URL);
  50. // this._socket.onmessage = (event) => {
  51. // const data = JSON.parse(event.data);
  52. // const handler = this.commandHandlers[data.command];
  53. // if (handler) {
  54. // handler.call(this, data);
  55. // }
  56. // };
  57. // }
  58. // handleCommand1(data: any) {
  59. // // 处理指令1的逻辑
  60. // }
  61. // handleCommand2(data: any) {
  62. // // 处理指令2的逻辑
  63. // }
  64. // // ... 其他指令处理函数
  65. // }