Esempio n. 1
0
        /// <summary>
        /// Start the client and attempt to connect to the server until the timeout is reached.
        /// </summary>
        /// <param name="timeout">Timeout in seconds.</param>
        /// <param name="token">Cancellation token to terminate connection attempts.</param>
        /// <returns>Task returning Boolean indicating if the connection was successful.</returns>
        public async Task <bool> StartWithTimeoutAsync(int timeout = 30, CancellationToken token = default)
        {
            if (timeout < 1)
            {
                throw new ArgumentException("Timeout must be greater than zero seconds.");
            }

            _Stats = new Statistics();
            if (_AcceptInvalidCertificates)
            {
                SetInvalidCertificateAcceptance();
            }

            Stopwatch sw      = new Stopwatch();
            TimeSpan  timeOut = TimeSpan.FromSeconds(timeout);

            sw.Start();

            try
            {
                while (sw.Elapsed < timeOut)
                {
                    if (token.IsCancellationRequested)
                    {
                        break;
                    }
                    _ClientWs = new ClientWebSocket();

                    _ClientWs.Options.Cookies           = _Cookies;
                    _ClientWs.Options.KeepAliveInterval = TimeSpan.FromSeconds(_KeepAliveIntervalSeconds);
                    if (_PreConfigureOptions != null)
                    {
                        _PreConfigureOptions(_ClientWs.Options);
                    }

                    try
                    {
                        await _ClientWs.ConnectAsync(_ServerUri, token).ContinueWith(AfterConnect);
                    }
                    catch (TaskCanceledException)
                    {
                        return(false);
                    }
                    catch (OperationCanceledException)
                    {
                        return(false);
                    }
                    catch (WebSocketException)
                    {
                        // do nothing
                    }

                    await Task.Delay(100);

                    // Check if connected
                    if (_ClientWs.State == WebSocketState.Open)
                    {
                        return(true);
                    }
                }
            }
            catch (TaskCanceledException)
            {
            }
            catch (OperationCanceledException)
            {
            }

            return(false);
        }