| 1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889 | using System;using System.Collections.Generic;using System.Linq;using System.Text;using System.Threading.Tasks;using WebSocketSharp;using Socket = WebSocketSharp.WebSocket;using Logger = InABox.Core.Logger;using InABox.Core;using InABox.WebSocket.Shared;using InABox.Clients;using InABox.Core.Notifications;namespace InABox.Client.WebSocket{    public class WebSocketClient : IDisposable    {        private Socket Socket;        private Guid Session;        private bool Closed = false;        public WebSocketClient(string url, int port, Guid session)        {            Session = session;            Socket = new Socket($"ws://{url}:{port}/notify");            Socket.OnOpen += Socket_OnOpen;            Socket.OnError += Socket_OnError;            Socket.OnClose += Socket_OnClose;            Socket.OnMessage += Socket_OnMessage;            Socket.Connect();            // Time to wait before disconnect - the default meant that the client disconnected during debugging, since the ping would fail            Socket.WaitTime = TimeSpan.FromMinutes(10);         }        private void Socket_OnMessage(object? sender, MessageEventArgs e)        {            var message = SocketMessage.ReadMessage(e.RawData);            if(message is NotifyMessage notify)            {                var notifyType = CoreUtils.GetEntity(notify.EntityType);                var notification = Serialization.Deserialize(notifyType, notify.EntityData);                ClientFactory.Notifications.Notify(notifyType, notification);            }            else if(message is InitialMessage)            {            }        }        private void Socket_OnOpen(object? sender, EventArgs e)        {            Logger.Send(LogType.Information, "", "WebSocket connected to server");            var initial = new InitialMessage(Session, Platform.Other);            Socket.Send(initial.WriteToBytes());        }        private void Socket_OnClose(object? sender, CloseEventArgs e)        {            Logger.Send(LogType.Information, "", "WebSocket disconnected from server");            if (!Closed)            {                Task.Run(() =>                {                    if (!Socket.IsAlive)                    {                        Task.Delay(30_000).Wait(); // Try to reconnect after 30 seconds                        Socket.Connect();                    }                });            }        }        private void Socket_OnError(object? sender, WebSocketSharp.ErrorEventArgs e)        {            Logger.Send(LogType.Error, "", $"WebSocket Error: {e.Message}");        }        public void Dispose()        {            Closed = true;            if (Socket.IsAlive)            {                Socket.Close();            }        }    }}
 |