SocketIOClientManager.cs 1.9 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374
  1. /// <summary>
  2. /// Copyright (c) 2025 MirzkisD1Ex0 All rights reserved.
  3. /// Code Version 1.5.2
  4. /// </summary>
  5. using System;
  6. using System.Collections;
  7. using System.Collections.Generic;
  8. using Best.SocketIO;
  9. using Best.SocketIO.Events;
  10. using ToneTuneToolkit.Common;
  11. using UnityEngine;
  12. using UnityEngine.Events;
  13. namespace ToneTuneToolkit.Networking
  14. {
  15. /// <summary>
  16. /// SocketIO通信
  17. /// </summary>
  18. public class SocketIOClientManager : SingletonMaster<SocketIOClientManager>
  19. {
  20. public static UnityAction<string> OnDeviceStart;
  21. private const string Address = @"wss://node.skyelook.com"; // 开头为wss且结尾并非/socket.io
  22. // private const string Address = "ws://192.168.50.130:3500";
  23. private SocketManager socketManager;
  24. // ==================================================
  25. private void Start() => Init();
  26. private void OnDestroy() => UnInit();
  27. // ==================================================
  28. private void Init()
  29. {
  30. socketManager = new SocketManager(new Uri(Address));
  31. socketManager.Options.AutoConnect = false;
  32. socketManager.Socket.On<ConnectResponse>(SocketIOEventTypes.Connect, OnConnected);
  33. socketManager.Socket.On<ConnectResponse>(SocketIOEventTypes.Error, OnError);
  34. socketManager.Socket.On<string>("michelin-start", OnStart);
  35. socketManager.Open();
  36. }
  37. private void UnInit()
  38. {
  39. if (socketManager != null)
  40. {
  41. socketManager.Close();
  42. socketManager = null;
  43. }
  44. }
  45. // ==================================================
  46. private void OnConnected(ConnectResponse resp)
  47. {
  48. Debug.Log("[SocketIOM] Connected.");
  49. }
  50. private void OnError(ConnectResponse resp)
  51. {
  52. Debug.Log(@$"[SocketIOM] {resp}");
  53. }
  54. private void OnStart(string value)
  55. {
  56. Debug.Log(@$"[SocketIOM] Start. {value}");
  57. OnDeviceStart?.Invoke(value);
  58. }
  59. }
  60. }