diff --git a/Models/AppSettings.cs b/Models/AppSettings.cs index e32641f..eb214a4 100644 --- a/Models/AppSettings.cs +++ b/Models/AppSettings.cs @@ -188,6 +188,7 @@ static Settings() { /// public bool WebSocketEnabled { get; set; } = false; public bool WebTrackerCompatibility { get; set; } = true; + public int WebSocketPort { get; set; } = 11398; /// /// Import a settings instance from the local json file diff --git a/Utils/API/WebSocketAPI.cs b/Utils/API/WebSocketAPI.cs index a155b4c..5e94690 100644 --- a/Utils/API/WebSocketAPI.cs +++ b/Utils/API/WebSocketAPI.cs @@ -16,7 +16,7 @@ namespace ToNSaveManager.Utils.API { internal class WebSocketAPI : WebSocketBehavior { - static readonly LoggerSource Logger = new LoggerSource("WS-API"); + static readonly LoggerSource Logger = new LoggerSource(nameof(WebSocketAPI)); internal static WebSocketServer? Server; protected override void OnMessage(MessageEventArgs e) { @@ -30,20 +30,21 @@ protected override void OnOpen() { Args = EventBuffer.ToArray(), DisplayName = ToNLogContext.Instance?.DisplayName ?? string.Empty, UserID = ToNLogContext.Instance?.UserID ?? string.Empty - }); - - SendValue("INSTANCE", ToNLogContext.Instance?.InstanceID); + }, this); + + SendEvent(new EventValue("INSTANCE", ToNLogContext.Instance?.InstanceID), this); // Send All Stats foreach (string key in ToNStats.PropertyKeys) { - WebSocketAPI.EventStats.Send(key, ToNStats.Get(key)); + SendEvent(new EventStats() { Name = key, Value = ToNStats.Get(key) }, this); } } + const int DEFAULT_PORT = 11398; internal static void Initialize() { if (Settings.Get.WebSocketEnabled && Server == null) { - const string url = "ws://localhost:11398"; - Server = new WebSocketServer(url); + int port = Settings.Get.WebSocketPort > 0 ? Settings.Get.WebSocketPort : DEFAULT_PORT; + Server = new WebSocketServer(port); Server.AddWebSocketService("/"); } @@ -62,10 +63,24 @@ internal static void Broadcast(string data) { Logger.Debug("Broadcasting: " + data); Server?.WebSocketServices?.Broadcast(data); } - internal static void SendObject(object data) => Broadcast(JsonConvert.SerializeObject(data)); - internal static void SendEvent(T value) where T : IEvent - { - if (Settings.Get.WebSocketEnabled) SendObject(value); + internal static void SendEvent(T value, WebSocketAPI? connection) where T : IEvent { + if (!Settings.Get.WebSocketEnabled) return; + string jsonData = JsonConvert.SerializeObject(value); + + try { + if (connection != null) { + Logger.Debug("Sending: " + jsonData); + connection.Send(jsonData); + return; + } + + Broadcast(jsonData); + } catch (Exception e) { + Logger.Error(e); +#if DEBUG + throw; +#endif + } } public interface IEvent { @@ -236,7 +251,7 @@ private static void QueueEvent(IEvent ev, bool buffer = true) { internal static void SendEventUpdate() { while (EventQueue.Count > 0) { - SendEvent(EventQueue.Dequeue()); + SendEvent(EventQueue.Dequeue(), null); } }