< Summary - ReFlex - Library

Information
Class: ReFlex.Core.Networking.Components.WebSocketServer
Assembly: ReFlex.Core.Networking
File(s): D:\a\reflex\reflex\library\src\Core\Networking\Components\WebSocketServer.cs
Line coverage
0%
Covered lines: 0
Uncovered lines: 91
Coverable lines: 91
Total lines: 208
Line coverage: 0%
Branch coverage
0%
Covered branches: 0
Total branches: 44
Branch coverage: 0%
Method coverage

Feature is only available for sponsors

Upgrade to PRO version

Metrics

MethodBranch coverage Crap Score Cyclomatic complexity Line coverage
.cctor()100%210%
.ctor(...)100%210%
get_Port()100%210%
get_Endpoint()100%210%
get_Type()100%210%
get_IsReady()100%210%
get_IsStarted()100%210%
get_Id()100%210%
get_Address()100%210%
set_Address(...)0%620%
Init(...)0%620%
Start()0%4260%
Stop()0%4260%
Broadcast(...)0%2040%
Broadcast(...)0%7280%
Broadcast(...)0%7280%
InitServices()100%210%
OnGet(...)0%4260%
Dispose()0%620%

File(s)

D:\a\reflex\reflex\library\src\Core\Networking\Components\WebSocketServer.cs

#LineLine coverage
 1using System;
 2using System.Net;
 3using System.Text;
 4using NLog;
 5using ReFlex.Core.Common.Components;
 6using ReFlex.Core.Networking.Interfaces;
 7using ReFlex.Core.Networking.Util;
 8using WebSocketSharp.Server;
 9using Logger = NLog.Logger;
 10
 11namespace ReFlex.Core.Networking.Components
 12{
 13    /// <summary>
 14    /// Can broadcast messages or objects to connected clients via http protocol.
 15    /// </summary>
 16    /// <seealso cref="IServer" />
 17    /// <inheritdoc />
 18    public class WebSocketServer : IServer, IDisposable
 19    {
 020        private static readonly Logger Logger = LogManager.GetCurrentClassLogger();
 21
 22        protected HttpServer Server;
 23        private IPAddress _address;
 024        private readonly Guid _serverId = Guid.NewGuid();
 25
 026        protected int Port { get; private set; }
 27
 028        protected string Endpoint { get; private set; }
 29
 030        public NetworkInterface Type => NetworkInterface.Websockets;
 31
 32        /// <summary>
 33        /// Gets a value indicating whether this instance is ready.
 34        /// </summary>
 35        /// <value>
 36        ///   <c>true</c> if this instance is ready; otherwise, <c>false</c>.
 37        /// </value>
 38        /// <inheritdoc />
 039        public bool IsReady => Server != null;
 40
 41        /// <summary>
 42        /// Gets a value indicating whether this instance is started.
 43        /// </summary>
 44        /// <value>
 45        ///   <c>true</c> if this instance is started; otherwise, <c>false</c>.
 46        /// </value>
 047        public bool IsStarted { get; private set; }
 48
 49
 050        public string Id => _serverId.ToString();
 51
 52        public string Address
 53        {
 054            get => $"{_address}:{Port}{Endpoint}";
 55            set
 056            {
 057                var p1 = value.IndexOf(':');
 058                var ipAddress = _address.ToString();
 59
 060                if (p1 > 0)
 061                {
 062                   ipAddress =  value.Substring(0, p1);
 063                }
 64
 065                var portAndEndpoint = value.Substring(p1 + 1);
 066                var p2 = portAndEndpoint.IndexOf('/');
 067                var success = int.TryParse(portAndEndpoint.Substring(0, p2), out var port);
 068                var endpoint = portAndEndpoint.Substring(p2);
 69
 070                Stop();
 71
 072                Init(ipAddress, port, endpoint);
 073            }
 74        }
 75
 76        /// <summary>
 77        ///
 78        /// </summary>
 79        /// <param name="ipAddress">the ip address of the server</param>
 80        /// <param name="endpoint">the path for the websocket (e.g. "/MyService")</param>
 081        public WebSocketServer(string ipAddress, int port, string endpoint)
 082        {
 083            Init(ipAddress, port, endpoint);
 084        }
 85
 86        private void Init(string ipAddress, int port, string endpoint)
 087        {
 088            Port = port;
 089            IsStarted = false;
 090            var success = IPAddress.TryParse(ipAddress, out _address);
 091            if (!success)
 092                throw new ArgumentOutOfRangeException($"Provided IP Address {ipAddress} is not valid for {GetType().Name
 93
 094            Endpoint = endpoint;
 095        }
 96
 97        /// <summary>
 98        /// Starts the websocket using the specified port.
 99        /// </summary>
 100        /// <param name="port">The port.</param>
 101        /// <inheritdoc />
 102        public void Start()
 0103        {
 0104            if (IsStarted)
 0105                return;
 106
 0107            Server = new HttpServer(_address, Port);
 0108            InitServices();
 109
 0110            Server.OnGet += OnGet;
 111
 0112            try {
 113
 0114            Server.Start();
 0115            IsStarted = true;
 116
 0117            } catch (Exception exc) {
 0118                Logger.Error(exc, $"{exc.GetType().Name} when starting {GetType().Name}: {exc?.Message}{Environment.NewL
 0119            }
 120
 0121        }
 122
 123        /// <summary>
 124        /// Stops this instance.
 125        /// </summary>
 126        /// <inheritdoc />
 127        public void Stop()
 0128        {
 0129            if (!IsStarted)
 0130                return;
 131
 132
 0133            Server?.Stop();
 0134            if (Server != null)
 0135                Server.OnGet -= OnGet;
 0136            IsStarted = false;
 0137        }
 138
 139        /// <summary>
 140        /// Broadcasts the specified data.
 141        /// </summary>
 142        /// <param name="data">The data.</param>
 143        /// <inheritdoc />
 144        public void Broadcast(object data)
 0145        {
 0146            if (IsReady && IsStarted)
 0147                Broadcast(SerializationUtils.SerializeToJson(data));
 0148        }
 149
 150        /// <summary>
 151        /// Broadcasts the specified data.
 152        /// </summary>
 153        /// <param name="data">The data.</param>
 154        /// <inheritdoc />
 155        public void Broadcast(byte[] data)
 0156        {
 0157            if (IsReady && IsStarted)
 0158                Server?.WebSocketServices?.Broadcast(data);
 0159        }
 160
 161        /// <summary>
 162        /// Broadcasts the specified data.
 163        /// </summary>
 164        /// <param name="data">The data.</param>
 165        /// <inheritdoc />
 166        public void Broadcast(string data)
 0167        {
 0168            if (IsReady && IsStarted)
 0169                Server?.WebSocketServices?.Broadcast(data);
 0170        }
 171
 172        protected virtual void InitServices()
 0173        {
 0174            Server.AddWebSocketService<BroadcastService>(Endpoint);
 0175        }
 176
 177        /// <summary>
 178        /// Called when [get].
 179        /// </summary>
 180        /// <param name="sender">The sender.</param>
 181        /// <param name="args">The <see cref="HttpRequestEventArgs"/> instance containing the event data.</param>
 182        private static void OnGet(object sender, HttpRequestEventArgs args)
 0183        {
 0184            var request = args.Request;
 0185            var response = args.Response;
 186
 0187            var path = request.RawUrl;
 0188            if (path == "/")
 0189                path += "index.html";
 190
 0191            if (path.EndsWith(".html"))
 0192            {
 0193                response.ContentType = "text/html";
 0194                response.ContentEncoding = Encoding.UTF8;
 0195            }
 0196            else if (path.EndsWith(".js"))
 0197            {
 0198                response.ContentType = "application/javascript";
 0199                response.ContentEncoding = Encoding.UTF8;
 0200            }
 0201        }
 202
 203        public void Dispose()
 0204        {
 0205            Server?.Stop();
 0206        }
 207    }
 208}