Пример #1
0
 private void Init()
 {
     foreach (string symbolName in SymbolsContainer.GetSymbolNames())
     {
         TraderStatistic.Add(new TraderInfo(SymbolsContainer.GetSymbol(symbolName)));
     }
     _connection.OrderStatusEvent   += OrderStatusHandler;
     _connection.OrderFilledEvent   += OrderFilledHandler;
     _connection.TraderBalanceEvent += TraderBalanceHandler;
     _connection.TraderStatusEvent  += TraderStatusHandler;
     _connection.FundingEvent       += FundingHandler;
     _connection.OrderCanceledEvent += OrderCanceledHandler;
     _connection.LeverageEvent      += LeverageHandler;
     _connection.ErrorEvent         += ErrorHandler;
     _connection.ControlConnected   += () =>
     {
         UpdateTraderStatus();
         Connected?.Invoke();
     };
     _connection.ControlReconnected += () => {
         UpdateTraderStatus();
         Reconnected?.Invoke();
     };
     _connection.ControlDisconnected += () => Disconnected?.Invoke();
 }
Пример #2
0
 /// <summary>
 /// Connects to client.
 /// </summary>
 /// <returns>A Task that can be awaited</returns>
 protected virtual async Task ConnectToClient()
 {
     using (HttpClient client = new HttpClient())
     {
         if (hasConnected)
         {
             Reconnecting?.Invoke();
         }
         client.DefaultRequestHeaders.Authorization = new System.Net.Http.Headers.AuthenticationHeaderValue("Bearer", accessToken);
         using (var stream = await client.GetStreamAsync(streamUri))
         {
             if (ReadTimeout > 0)
             {
                 stream.ReadTimeout = ReadTimeout;
             }
             if (!hasConnected)
             {
                 Connected?.Invoke();
                 hasConnected = true;
             }
             else
             {
                 Reconnected?.Invoke();
             }
             await ListensToStreamAsync(stream).ConfigureAwait(true);
         }
     }
 }
Пример #3
0
 /// <summary>
 /// Called when the internal SignalR client has successfully reconnected.
 /// </summary>
 /// <param name="sender">The sender.</param>
 /// <param name="e">The <see cref="EventArgs"/> instance containing the event data.</param>
 protected virtual void OnReconnected(object sender, EventArgs e)
 {
     if (State == ResonanceComponentState.Connected)
     {
         Reconnected?.Invoke(this, e);
     }
 }
Пример #4
0
        private async void MediaStreamSource_SampleRequested(MediaStreamSource sender, MediaStreamSourceSampleRequestedEventArgs args)
        {
            var  request   = args.Request;
            var  deferral  = request.GetDeferral();
            bool connected = true;

            try
            {
                cancelTokenSource.Token.ThrowIfCancellationRequested();

                try
                {
                    await ReadSampleAsync(request).ConfigureAwait(false);

                    cancelTokenSource.Token.ThrowIfCancellationRequested();
                }
                catch (ShoutcastDisconnectionException)
                {
                    //Reset and reconnect.
                    DisconnectSockets();
                    connected = false;
                }
                catch (COMException ex)
                {
                    //Usually this is thrown when we get disconnected because of inactivity.
                    //Reset and reconnect.
                    DisconnectSockets();
                    connected = false;
                }

                cancelTokenSource.Token.ThrowIfCancellationRequested();
                if (!connected)
                {
                    try
                    {
                        await ReconnectSocketsAsync().ConfigureAwait(false);

                        Reconnected?.Invoke(this, EventArgs.Empty);

                        await ReadSampleAsync(request).ConfigureAwait(false);
                    }
                    catch (Exception)
                    {
                        MediaStreamSource.NotifyError(MediaStreamSourceErrorStatus.ConnectionToServerLost);
                    }
                }
            }
            catch (OperationCanceledException)
            {
            }
            catch (Exception)
            {
                MediaStreamSource.NotifyError(MediaStreamSourceErrorStatus.Other);
            }
            finally
            {
                deferral.Complete();
            }
        }
Пример #5
0
        public HubConfigurator(TaskFactory sync)
        {
            Hub = new HubConnection(Settings.Default.server);

            this.sync = sync;

            Hub.Closed       += () => sync.StartNew(() => Disconnected?.Invoke());
            Hub.Reconnected  += () => sync.StartNew(() => Reconnected?.Invoke());
            Hub.Reconnecting += () => sync.StartNew(() => Reconnecting?.Invoke());

            Hub.Received += Console.WriteLine;
        }
        /// <summary>
        /// Called when the internal SignalR client has successfully reconnected.
        /// </summary>
        /// <param name="sender">The sender.</param>
        /// <param name="e">The <see cref="EventArgs"/> instance containing the event data.</param>
        protected async virtual void OnReconnected(object sender, EventArgs e)
        {
            try
            {
                await _client.InvokeAsync(ResonanceHubMethods.Login, Credentials);
                await RegisterAsync();

                Reconnected?.Invoke(this, new EventArgs());
            }
            catch (Exception ex)
            {
                Error?.Invoke(this, new ResonanceExceptionEventArgs(ex));
            }
        }
Пример #7
0
        private void ReadCompleted(IAsyncResult result)
        {
            int readBytes = clientStream.EndRead(result);

            if (readBytes > 0)
            {
                messageBuilder.Append(Encoding.UTF8.GetString(buffer, 0, readBytes));

                if (!clientStream.IsMessageComplete)
                {
                    clientStream.BeginRead(buffer, 0, buffer.Length, ReadCompleted, null);
                }
                else
                {
                    string message = messageBuilder.ToString().TrimEnd('\0');
                    messageBuilder.Clear();
                    if (messageBuilder.Capacity > 64 * 1024)
                    {
                        messageBuilder.Capacity = buffer.Length;
                    }
                    synchronizationContext.Post(
                        a => Message?.Invoke(this, (NamedPipeClientMessageEventArgs)a),
                        new NamedPipeClientMessageEventArgs(this)
                    {
                        Message = message
                    });

                    // Continue reading for next message
                    clientStream.BeginRead(buffer, 0, buffer.Length, ReadCompleted, null);
                }
            }
            else
            {
                if (!isDisposed)
                {
                    synchronizationContext.Post(a => Disconnected?.Invoke(this, (EventArgs)a), EventArgs.Empty);
                    if (Reconnect)
                    {
                        Connect(Timeout.Infinite);
                        synchronizationContext.Post(a => Reconnected?.Invoke(this, (EventArgs)a), EventArgs.Empty);
                    }
                    else
                    {
                        Dispose();
                    }
                }
            }
        }
Пример #8
0
        protected void InitConnection()
        {
            Connection.Closed += ex0 => Task.Run(() =>
            {
                if (ex0 == null || !AutomaticRetry)
                {
                    HandleClosed(ex0);
                    return;
                }

                Exception?.Invoke(this, ex0);
                Thread.Sleep(ExceptionRetryDelay);
                try
                {
                    Running = false;
                    StartAsync(AutomaticRetry, ex0).Wait();
                    Reconnected?.Invoke(this, ex0);
                }
                catch (Exception ex)
                {
                    HandleClosed(ex);
                }
            });
        }
Пример #9
0
        /// <summary>
        /// Starts the connection.
        /// </summary>
        /// <returns></returns>
        public Task StartAsync()
        {
            if (IsStarted)
            {
                return(Task.FromResult(true));
            }

            TaskCompletionSource <object> completion = new TaskCompletionSource <object>();

            bool completed = false;

            Task.Factory.StartNew(() =>
            {
                try
                {
                    var urlHub  = SplitUrl(Url);
                    _connection = new HubConnection(urlHub.url);
                    _proxy      = _connection.CreateHubProxy(urlHub.hub);
                    _connection.StateChanged += (x) =>
                    {
                        if (x.NewState == ConnectionState.Connected)
                        {
                            if (!completed)
                            {
                                IsStarted = true;
                                completed = true;
                                completion.SetResult(true);
                            }
                        }
                    };

                    bool reconnecting = false;

                    _connection.Error += (exception) =>
                    {
                        if (EnableAutoReconnection)
                        {
                            if (reconnecting && _connection.State == ConnectionState.Reconnecting && exception.GetType() == typeof(TimeoutException))
                            {
                                Error?.Invoke(this, new ResonanceExceptionEventArgs(exception));
                            }
                        }
                    };

                    _connection.Reconnecting += () =>
                    {
                        if (!reconnecting)
                        {
                            reconnecting = true;

                            if (EnableAutoReconnection)
                            {
                                Reconnecting?.Invoke(this, new EventArgs());
                            }
                            else if (_connection.LastError != null)
                            {
                                try
                                {
                                    Stop();
                                    Error?.Invoke(this, new ResonanceExceptionEventArgs(_connection.LastError));
                                }
                                catch { }
                            }
                        }
                    };

                    _connection.Reconnected += () =>
                    {
                        if (EnableAutoReconnection)
                        {
                            reconnecting = false;
                            Reconnected?.Invoke(this, new EventArgs());
                        }
                    };

                    _connection.Start();
                }
                catch (Exception ex)
                {
                    if (!completed)
                    {
                        completed = true;
                        completion.SetException(ex);
                    }
                }
            });

            TimeoutTask.StartNew(() =>
            {
                if (!completed)
                {
                    completed = true;
                    completion.SetException(new TimeoutException("Could not establish the connection within the given timeout."));
                }
            }, TimeSpan.FromSeconds(10));

            return(completion.Task);
        }
Пример #10
0
 protected virtual void OnReconnected(EventArgs e)
 {
     Reconnected?.Invoke(this, e);
 }
Пример #11
0
        /// <summary>
        /// Starts the connection.
        /// </summary>
        /// <returns></returns>
        public async Task StartAsync()
        {
            if (IsStarted)
            {
                return;
            }


            var builder = new HubConnectionBuilder().WithUrl(Url).WithAutomaticReconnect();

            if (UseMessagePackProtocol)
            {
                builder = builder.AddMessagePackProtocol();
            }

            if (EnableAutoReconnection)
            {
                builder = builder.WithAutomaticReconnect(new TimeSpan[]
                {
                    TimeSpan.FromSeconds(1),
                    TimeSpan.FromSeconds(1),
                    TimeSpan.FromSeconds(1),
                    TimeSpan.FromSeconds(1)
                });
            }

            _connection = builder.Build();

            bool reconnecting = false;

            _connection.Closed += (exception) =>
            {
                if (EnableAutoReconnection)
                {
                    if (reconnecting && _connection.State == HubConnectionState.Disconnected && exception.GetType() == typeof(OperationCanceledException))
                    {
                        Error?.Invoke(this, new ResonanceExceptionEventArgs(exception));
                    }
                }

                return(Task.FromResult(true));
            };

            _connection.Reconnecting += (ex) =>
            {
                if (!reconnecting)
                {
                    reconnecting = true;

                    if (EnableAutoReconnection)
                    {
                        Reconnecting?.Invoke(this, new EventArgs());
                    }
                    else
                    {
                        try
                        {
                            Stop();
                            Error?.Invoke(this, new ResonanceExceptionEventArgs(ex));
                        }
                        catch { }
                    }
                }

                return(Task.FromResult(true));
            };

            _connection.Reconnected += (msg) =>
            {
                if (EnableAutoReconnection)
                {
                    Reconnected?.Invoke(this, new EventArgs());
                    reconnecting = false;
                }

                return(Task.FromResult(true));
            };

            await _connection.StartAsync();

            IsStarted = true;
        }
Пример #12
0
 private void onReconnect(object sender, ConnEventArgs args)
 {
     Log.Info("Reconnected to NATS. Sending reset event.");
     ResetAll();
     Reconnected?.Invoke(this, EmptyServeEventArgs);
 }
Пример #13
0
 internal void InvokeReconnected()
 {
     Reconnected?.Invoke();
 }
Пример #14
0
 protected void OnReconnected() => Reconnected?.Invoke();
Пример #15
0
        // private
        private Task HubConnection_Reconnected(string arg)
        {
            Reconnected?.Invoke(arg);

            return(Task.CompletedTask);
        }
Пример #16
0
        public void Init(string url, string token)
        {
            if (_hubConnection != null)
            {
                return;
            }

            _hubConnection = new HubConnectionBuilder()
                             .WithUrl(url, options =>
            {
                /*
                 *  The access token function you provide is called before every HTTP request made by SignalR.
                 *  If you need to renew the token in order to keep the connection active
                 *  (because it may expire during the connection),
                 *  do so from within this function and return the updated token.
                 *  https://docs.microsoft.com/en-us/aspnet/core/signalr/authn-and-authz?view=aspnetcore-3.1#bearer-token-authentication
                 */
                options.AccessTokenProvider = () =>
                {
                    // verify access token here

                    // if not verified, refresh access token using refresh token

                    //Debug.WriteLine(token);
                    Debug.Assert(token != null);

                    return(Task.FromResult(token));
                };
            })
                             .WithAutomaticReconnect(new[]
            {
                // default: wait 0,2,10,30 seconds and try to reconnect
                TimeSpan.FromSeconds(0),
                TimeSpan.FromSeconds(1),
                TimeSpan.FromSeconds(2),
                TimeSpan.FromSeconds(1),
                TimeSpan.FromSeconds(2),
                TimeSpan.FromSeconds(1)
            })
                             .Build();

            // Handle Hub connection events
            _hubConnection.Closed += err =>
            {
                Closed?.Invoke(this, new ConnectionEventArgs($"Connection to SignalR Hub Closed. {err.Message}"));
                return(Task.CompletedTask);
            };
            _hubConnection.Reconnecting += err =>
            {
                Reconnecting?.Invoke(this, new ConnectionEventArgs($"Try to reconnect to SignarR Hub. current error message: {err.Message}"));
                return(Task.CompletedTask);
            };
            _hubConnection.Reconnected += connectionId =>
            {
                Reconnected?.Invoke(this, new ConnectionEventArgs($"Succesfully re-connected to SignalR hub. New Connectionid: {connectionId}"));
                return(Task.CompletedTask);
            };

            // Handle Hub messages
            _hubConnection.On <string, string, int, int, DateTime, string>("ReceiveMessage", ReceiveMessage);

            _hubConnection.On <string>("Entered", user =>
            {
                SomeoneEntered?.Invoke(this, new SignalREventArgs($"{user} entered.", user));
                //AddLocalMessage($"{user} entered.", user);
            });

            _hubConnection.On <string>("Left", user =>
            {
                SomeoneLeft?.Invoke(this, new SignalREventArgs($"{user} left.", user));
            });
        }
Пример #17
0
 void OnConnectionReconnected(object sender, EventArgs args)
 {
     Reconnected?.Invoke(this, args);
 }
Пример #18
0
 internal void InvokeReconnected(Client client, ReconnectionInfo info)
 {
     Reconnected?.Invoke(client, new ReconnectedEventArgs(info));
 }
Пример #19
0
 private void RaiseHubReconnect()
 {
     Reconnected.Invoke(IsConnected);
     Debug.WriteLine("RaiseHubReconnect raised! Hub on url " + HubUrl + " " +
                     "reconnected with status IsConnected = " + IsConnected);
 }
Пример #20
0
 private void OnReconnected()
 {
     Reconnected?.Invoke();
 }
Пример #21
0
 internal void OnReconnected()
 {
     Reconnected?.Invoke(this, EventArgs.Empty);
 }