SimpleWebClient.cs 2.9 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586
  1. using System;
  2. using System.Collections.Concurrent;
  3. using UnityEngine;
  4. namespace Mirror.SimpleWeb
  5. {
  6. public enum ClientState
  7. {
  8. NotConnected = 0,
  9. Connecting = 1,
  10. Connected = 2,
  11. Disconnecting = 3,
  12. }
  13. /// <summary>
  14. /// Client used to control websockets
  15. /// <para>Base class used by WebSocketClientWebGl and WebSocketClientStandAlone</para>
  16. /// </summary>
  17. public abstract class SimpleWebClient
  18. {
  19. public static SimpleWebClient Create(int maxMessageSize, int maxMessagesPerTick, TcpConfig tcpConfig)
  20. {
  21. #if UNITY_WEBGL && !UNITY_EDITOR
  22. return new WebSocketClientWebGl(maxMessageSize, maxMessagesPerTick);
  23. #else
  24. return new WebSocketClientStandAlone(maxMessageSize, maxMessagesPerTick, tcpConfig);
  25. #endif
  26. }
  27. readonly int maxMessagesPerTick;
  28. protected readonly int maxMessageSize;
  29. protected readonly ConcurrentQueue<Message> receiveQueue = new ConcurrentQueue<Message>();
  30. protected readonly BufferPool bufferPool;
  31. protected ClientState state;
  32. protected SimpleWebClient(int maxMessageSize, int maxMessagesPerTick)
  33. {
  34. this.maxMessageSize = maxMessageSize;
  35. this.maxMessagesPerTick = maxMessagesPerTick;
  36. bufferPool = new BufferPool(5, 20, maxMessageSize);
  37. }
  38. public ClientState ConnectionState => state;
  39. public event Action onConnect;
  40. public event Action onDisconnect;
  41. public event Action<ArraySegment<byte>> onData;
  42. public event Action<Exception> onError;
  43. public void ProcessMessageQueue(MonoBehaviour behaviour)
  44. {
  45. int processedCount = 0;
  46. // check enabled every time in case behaviour was disabled after data
  47. while (
  48. behaviour.enabled &&
  49. processedCount < maxMessagesPerTick &&
  50. // Dequeue last
  51. receiveQueue.TryDequeue(out Message next)
  52. )
  53. {
  54. processedCount++;
  55. switch (next.type)
  56. {
  57. case EventType.Connected:
  58. onConnect?.Invoke();
  59. break;
  60. case EventType.Data:
  61. onData?.Invoke(next.data.ToSegment());
  62. next.data.Release();
  63. break;
  64. case EventType.Disconnected:
  65. onDisconnect?.Invoke();
  66. break;
  67. case EventType.Error:
  68. onError?.Invoke(next.exception);
  69. break;
  70. }
  71. }
  72. }
  73. public abstract void Connect(Uri serverAddress);
  74. public abstract void Disconnect();
  75. public abstract void Send(ArraySegment<byte> segment);
  76. }
  77. }