WebSocketClient.cs 2.8 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889
  1. using System;
  2. using System.Collections.Generic;
  3. using System.Linq;
  4. using System.Text;
  5. using System.Threading.Tasks;
  6. using WebSocketSharp;
  7. using Socket = WebSocketSharp.WebSocket;
  8. using Logger = InABox.Core.Logger;
  9. using InABox.Core;
  10. using InABox.WebSocket.Shared;
  11. using InABox.Clients;
  12. using InABox.Core.Notifications;
  13. namespace InABox.Client.WebSocket
  14. {
  15. public class WebSocketClient : IDisposable
  16. {
  17. private Socket Socket;
  18. private Guid Session;
  19. private bool Closed = false;
  20. public WebSocketClient(string url, int port, Guid session)
  21. {
  22. Session = session;
  23. Socket = new Socket($"ws://{url}:{port}/notify");
  24. Socket.OnOpen += Socket_OnOpen;
  25. Socket.OnError += Socket_OnError;
  26. Socket.OnClose += Socket_OnClose;
  27. Socket.OnMessage += Socket_OnMessage;
  28. Socket.Connect();
  29. // Time to wait before disconnect - the default meant that the client disconnected during debugging, since the ping would fail
  30. Socket.WaitTime = TimeSpan.FromMinutes(10);
  31. }
  32. private void Socket_OnMessage(object? sender, MessageEventArgs e)
  33. {
  34. var message = SocketMessage.ReadMessage(e.RawData);
  35. if(message is NotifyMessage notify)
  36. {
  37. var notifyType = CoreUtils.GetEntity(notify.EntityType);
  38. var notification = Serialization.Deserialize(notifyType, notify.EntityData);
  39. ClientFactory.Notifications.Notify(notifyType, notification);
  40. }
  41. else if(message is InitialMessage)
  42. {
  43. }
  44. }
  45. private void Socket_OnOpen(object? sender, EventArgs e)
  46. {
  47. Logger.Send(LogType.Information, "", "WebSocket connected to server");
  48. var initial = new InitialMessage(Session, Platform.Other);
  49. Socket.Send(initial.WriteToBytes());
  50. }
  51. private void Socket_OnClose(object? sender, CloseEventArgs e)
  52. {
  53. Logger.Send(LogType.Information, "", "WebSocket disconnected from server");
  54. if (!Closed)
  55. {
  56. Task.Run(() =>
  57. {
  58. if (!Socket.IsAlive)
  59. {
  60. Task.Delay(30_000).Wait(); // Try to reconnect after 30 seconds
  61. Socket.Connect();
  62. }
  63. });
  64. }
  65. }
  66. private void Socket_OnError(object? sender, WebSocketSharp.ErrorEventArgs e)
  67. {
  68. Logger.Send(LogType.Error, "", $"WebSocket Error: {e.Message}");
  69. }
  70. public void Dispose()
  71. {
  72. Closed = true;
  73. if (Socket.IsAlive)
  74. {
  75. Socket.Close();
  76. }
  77. }
  78. }
  79. }