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. Uri uri = new Uri("http://" + url);
  24. Socket = new Socket($"ws://{uri.Host}:{port}/notify");
  25. Socket.OnOpen += Socket_OnOpen;
  26. Socket.OnError += Socket_OnError;
  27. Socket.OnClose += Socket_OnClose;
  28. Socket.OnMessage += Socket_OnMessage;
  29. Socket.Connect();
  30. // Time to wait before disconnect - the default meant that the client disconnected during debugging, since the ping would fail
  31. Socket.WaitTime = TimeSpan.FromMinutes(10);
  32. }
  33. private void Socket_OnMessage(object? sender, MessageEventArgs e)
  34. {
  35. var message = SocketMessage.ReadMessage(e.RawData);
  36. if(message is NotifyMessage notify)
  37. {
  38. var notifyType = CoreUtils.GetEntity(notify.EntityType);
  39. var notification = Serialization.Deserialize(notifyType, notify.EntityData);
  40. ClientFactory.Notifications.Notify(notifyType, notification);
  41. }
  42. else if(message is InitialMessage)
  43. {
  44. }
  45. }
  46. private void Socket_OnOpen(object? sender, EventArgs e)
  47. {
  48. Logger.Send(LogType.Information, "", "WebSocket connected to server");
  49. var initial = new InitialMessage(Session, Platform.Other);
  50. Socket.Send(initial.WriteToBytes());
  51. }
  52. private void Socket_OnClose(object? sender, CloseEventArgs e)
  53. {
  54. Logger.Send(LogType.Information, "", "WebSocket disconnected from server");
  55. if (!Closed)
  56. {
  57. Task.Run(() =>
  58. {
  59. if (!Socket.IsAlive)
  60. {
  61. Task.Delay(30_000).Wait(); // Try to reconnect after 30 seconds
  62. Socket.Connect();
  63. }
  64. });
  65. }
  66. }
  67. private void Socket_OnError(object? sender, WebSocketSharp.ErrorEventArgs e)
  68. {
  69. Logger.Send(LogType.Error, "", $"WebSocket Error: {e.Message}");
  70. }
  71. public void Dispose()
  72. {
  73. Closed = true;
  74. if (Socket.IsAlive)
  75. {
  76. Socket.Close();
  77. }
  78. }
  79. }
  80. }