예제 #1
0
        private void TryReconnect()
        {
            bool shouldTry;

            lock (registrationLock)
                shouldTry = registrations.Any();

            if (shouldTry)
            {
                if (!WaitForConnection())
                {
                    Thread.Sleep(5000);
                    Task.Run(() => TryReconnect());
                }
                else
                {
                    log.Write(LogVerbosity.Info, "Reconnected");
                    reconnecting = false;
                    ConnectionRestored?.Invoke();
                }
            }
            else
            {
                reconnecting = false;
            }
        }
예제 #2
0
        private bool HandleExceptions(Action action)
        {
            var  cancellationToken = _operationCancellationTokenSource.Token;
            bool success           = false;

            try
            {
                if (_credentials != null && (_serviceClient?.IsClosedOrFaulted ?? false))
                {
                    _serviceClient = ClientsManager.Create(_credentials.Value);
                }
                if (ConnectionState == ManagerConnectionState.Disconnected)
                {
                    ConnectionState = ManagerConnectionState.Connecting;
                }
                action();
                success = true;
                if (ConnectionState != ManagerConnectionState.Connected)
                {
                    ConnectionState = ManagerConnectionState.Connected;
                    ConnectionRestored?.Invoke();
                }
            }
            catch (System.Exception e)
            {
                if (!cancellationToken.IsCancellationRequested)
                {
                    if (SystemUtils.IsFaultExceptionHasCode(e, ServiceFaultCodes.AccessDenied))
                    {
                        LoginOrPasswordInvalid?.Invoke();
                    }
                    //if data is wrong or secretKey.Length is wrong
                    else if (
                        SystemUtils.IsFaultExceptionHasCode(e, ServiceFaultCodes.DecryptionError) ||
                        e is SerializationException ||
                        e is DecryptException ||
                        e.Message == "Key length not 128/192/256 bits.")
                    {
                        SecretCodeInvalid?.Invoke();
                    }
                    else if (ConnectionState != ManagerConnectionState.Connected)
                    {
                        ConnectionLost?.Invoke();
                    }
                    else
                    {
                        ConnectionError?.Invoke();
                    }
                    ConnectionState = ManagerConnectionState.Disconnected;
                    success         = false;
                }
            }
            if (cancellationToken.IsCancellationRequested)
            {
                return(false);
            }
            return(success);
        }
        private void Handler_HasCome(object sender, Message msg)
        {
            _toServiceMessenger = Utils.GetAnswerMessenger(msg);
            switch ((ServiceOperation)msg.What)
            {
            case ServiceOperation.GetClientSettings:
                _callbacks.Dequeue(ServiceOperation.GetClientSettings, Utils.GetData <ConnectionCredentials>(msg));
                break;

            case ServiceOperation.GetIsConnected:
                _callbacks.Dequeue(ServiceOperation.GetIsConnected, Utils.GetData <ManagerConnectionState>(msg));
                break;

            case ServiceOperation.GetScenarios:
                _callbacks.Dequeue(ServiceOperation.GetScenarios, Utils.GetData <ScenarioInfo[]>(msg));
                break;

            case ServiceOperation.GetNotifications:
                _callbacks.Dequeue(ServiceOperation.GetNotifications, Utils.GetData <LazuriteNotification[]>(msg));
                break;

            case ServiceOperation.ConnectionLost:
                ConnectionLost?.Invoke();
                break;

            case ServiceOperation.ConnectionRestored:
                ConnectionRestored?.Invoke();
                break;

            case ServiceOperation.CredentialsInvalid:
                LoginOrPasswordInvalid?.Invoke();
                break;

            case ServiceOperation.CredentialsLoaded:
                CredentialsLoaded?.Invoke();
                break;

            case ServiceOperation.NeedClientSettings:
                NeedClientSettings?.Invoke();
                break;

            case ServiceOperation.NeedRefresh:
                NeedRefresh?.Invoke();
                break;

            case ServiceOperation.ScenariosChanged:
                ScenariosChanged?.Invoke(Utils.GetData <ScenarioInfo[]>(msg));
                break;

            case ServiceOperation.SecretCodeInvalid:
                SecretCodeInvalid?.Invoke();
                break;

            case ServiceOperation.ConnectionError:
                ConnectionError?.Invoke();
                break;
            }
        }
예제 #4
0
        private void RaiseConnectionRestored(IMessageAdapter adapter)
        {
#pragma warning disable 618
            Restored?.Invoke();
#pragma warning restore 618

            if (adapter != null)
            {
                ConnectionRestored?.Invoke(adapter);
            }
        }
예제 #5
0
        private void onConnectionRestored()
        {
            if (isConnected())
            {
                Debug.Assert(false);
                return;
            }

            stopConnectionCheckingTimer();
            Trace.TraceInformation("[GitLabInstance] Connection restored ({0})", HostName);
            ConnectionRestored?.Invoke();
        }
예제 #6
0
 private void TryReconnect()
 {
     if (registrations.Any())
     {
         if (!WaitForConnection())
         {
             Thread.Sleep(5000);
             TryReconnect();
         }
         else
         {
             reconnecting = false;
             ConnectionRestored?.Invoke();
         }
     }
     reconnecting = false;
 }
예제 #7
0
        public SocketSubscription(IWebsocket socket)
        {
            Socket           = socket;
            Events           = new List <SocketEvent>();
            waitingForEvents = new List <SocketEvent>();

            MessageHandlers = new Dictionary <string, Func <SocketSubscription, JToken, bool> >();

            Socket.OnClose += () =>
            {
                if (lostTriggered)
                {
                    return;
                }

                Socket.DisconnectTime = DateTime.UtcNow;
                lostTriggered         = true;

                lock (eventLock)
                {
                    foreach (var events in Events)
                    {
                        events.Reset();
                    }
                }

                if (Socket.ShouldReconnect)
                {
                    ConnectionLost?.Invoke();
                }
            };
            Socket.OnOpen += () =>
            {
                if (lostTriggered)
                {
                    lostTriggered = false;
                    ConnectionRestored?.Invoke(Socket.DisconnectTime.HasValue ? DateTime.UtcNow - Socket.DisconnectTime.Value: TimeSpan.FromSeconds(0));
                }
            };
        }
예제 #8
0
        private void TryReconnect()
        {
            bool shouldTry = false;

            lock (registrationLock)
                shouldTry = registrations.Any();

            if (shouldTry)
            {
                if (!WaitForConnection())
                {
                    Thread.Sleep(5000);
                    TryReconnect();
                }
                else
                {
                    reconnecting = false;
                    ConnectionRestored?.Invoke();
                }
            }
            reconnecting = false;
        }
        public SocketConnection(SocketClient client, IWebsocket socket)
        {
            log          = client.log;
            socketClient = client;

            pendingRequests = new List <PendingRequest>();

            handlers = new List <SocketSubscription>();
            Socket   = socket;

            Socket.Timeout    = client.SocketNoDataTimeout;
            Socket.OnMessage += ProcessMessage;
            Socket.OnClose   += () =>
            {
                if (lostTriggered)
                {
                    return;
                }

                DisconnectTime = DateTime.UtcNow;
                lostTriggered  = true;

                if (ShouldReconnect)
                {
                    ConnectionLost?.Invoke();
                }
            };
            Socket.OnClose += SocketOnClose;
            Socket.OnOpen  += () =>
            {
                PausedActivity = false;
                Connected      = true;
                if (lostTriggered)
                {
                    lostTriggered = false;
                    ConnectionRestored?.Invoke(DisconnectTime.HasValue ? DateTime.UtcNow - DisconnectTime.Value: TimeSpan.FromSeconds(0));
                }
            };
        }
 /// <summary>
 /// Handles lidgren connection close event (fires Closed event).
 /// </summary>
 public override void OnConnectionClose()
 {
     if (!gracefulClosing && !attemptingReconnection)
     {
         ConnectionInterrupted?.Invoke();
         attemptingReconnection = true;
         PausedConnectionResponse response = new PausedConnectionResponse
         {
             ReconnectHost = Host,
             ReconnectPort = Port
         };
         while (!gracefulClosing && failures < RetryAttempts)
         {
             response.FailedAttempts = failures;
             ConnectionPaused?.Invoke(response);
             if (response.Abort)
             {
                 break;
             }
             NetConnection newConnection = Client.Connect(response.ReconnectHost, response.ReconnectPort);
             try
             {
                 newConnection.WaitForConnectionToOpen();
                 RestoreConnection(newConnection, response);
                 ConnectionRestored?.Invoke();
                 return;
             }
             catch (ConnectionOpenException)
             {
                 failures++;
             }
         }
         ConnectionAborted?.Invoke();
         AbortConnection();
     }
 }
예제 #11
0
 /// <summary>
 /// Event invocator for the <see cref="ConnectionRestored"/> event
 /// </summary>
 protected virtual void OnConnectionRestored()
 {
     ConnectionRestored?.Invoke(this, EventArgs.Empty);
 }
예제 #12
0
 private void OnConnectionRestored()
 {
     Log.Debug("On Connection Restored");
     ConnectionRestored?.Invoke(this, EventArgs.Empty);
 }
예제 #13
0
 private async void InvokeConnectionRestored()
 {
     await Task.Run(() => ConnectionRestored?.Invoke(DisconnectTime.HasValue ? DateTime.UtcNow - DisconnectTime.Value : TimeSpan.FromSeconds(0))).ConfigureAwait(false);
 }
예제 #14
0
        /// <summary>
        /// Handler for a socket closing. Reconnects the socket if needed, or removes it from the active socket list if not
        /// </summary>
        protected virtual void SocketOnClose()
        {
            if (socketClient.AutoReconnect && ShouldReconnect)
            {
                if (Socket.Reconnecting)
                {
                    return; // Already reconnecting
                }
                Socket.Reconnecting = true;

                log.Write(LogVerbosity.Info, $"Socket {Socket.Id} Connection lost, will try to reconnect after {socketClient.ReconnectInterval}");
                Task.Run(async() =>
                {
                    while (ShouldReconnect)
                    {
                        await Task.Delay(socketClient.ReconnectInterval).ConfigureAwait(false);
                        if (!ShouldReconnect)
                        {
                            // Should reconnect changed to false while waiting to reconnect
                            Socket.Reconnecting = false;
                            return;
                        }

                        Socket.Reset();
                        if (!await Socket.Connect().ConfigureAwait(false))
                        {
                            log.Write(LogVerbosity.Debug, $"Socket {Socket.Id} failed to reconnect");
                            continue;
                        }

                        var time       = DisconnectTime;
                        DisconnectTime = null;

                        log.Write(LogVerbosity.Info, $"Socket {Socket.Id} reconnected after {DateTime.UtcNow - time}");

                        var reconnectResult = await ProcessReconnect().ConfigureAwait(false);
                        if (!reconnectResult)
                        {
                            await Socket.Close().ConfigureAwait(false);
                        }
                        else
                        {
                            if (lostTriggered)
                            {
                                lostTriggered = false;
                                Task.Run(() => ConnectionRestored?.Invoke(DisconnectTime.HasValue ? DateTime.UtcNow - DisconnectTime.Value : TimeSpan.FromSeconds(0)));
                            }

                            break;
                        }
                    }

                    Socket.Reconnecting = false;
                });
            }
            else
            {
                log.Write(LogVerbosity.Info, $"Socket {Socket.Id} closed");
                Socket.Dispose();
                Closed?.Invoke();
            }
        }
예제 #15
0
 /// <summary>
 /// Event invocator for the <see cref="ConnectionRestored"/> event
 /// </summary>
 protected virtual void OnConnectionRestored()
 {
     Log.Trace("DefaultConnectionHandler.OnConnectionRestored(): WebSocket connection restored.");
     ConnectionRestored?.Invoke(this, EventArgs.Empty);
 }