Пример #1
0
        public HubClient()
        {
            //var builder = new ConfigurationBuilder().AddJsonFile("JsonFile/class.json");
            var    builder = new ConfigurationBuilder().AddJsonFile("SignalRClient.json");
            var    config  = builder.Build();
            string url     = config["SignalRUrl"];

            connection = new HubConnectionBuilder()
                         //.WithUrl("http://localhost:667/ChatHub")
                         .WithUrl(url)
                         .Build();

            connection.Closed += async(error) =>
            {
                MessageManager.Instance.WriteErrorLine("客户端已离线,即将自动重连 ... ...");
                await Task.Delay(new Random().Next(0, 5) * 1000);

                //MessageManager.Instance.WriteErrorLine("启动自动重连 ... ...");
                //try
                //{
                //    await connection.StartAsync();
                //    Register();
                //}
                //catch (Exception ex)
                //{
                //    MessageManager.Instance.WriteErrorLine(ex.ToString());
                //}
                Reconnection(1);
            };
        }
Пример #2
0
        public async Task ConnectStatusStreamAsync()
        {
            if (_connectionConfig.ServerMode == "v1")
            {
                // older signalr client/server
                _legacyConnection = new Microsoft.AspNet.SignalR.Client.HubConnection(_statusHubUri);
                _legacyConnection.Credentials = System.Net.CredentialCache.DefaultCredentials;

                var hubProxy = _legacyConnection.CreateHubProxy("StatusHub");

                hubProxy.On<ManagedCertificate>(Providers.StatusHubMessages.SendManagedCertificateUpdateMsg, (u) => OnManagedCertificateUpdated?.Invoke(u));
                hubProxy.On<RequestProgressState>(Providers.StatusHubMessages.SendProgressStateMsg, (s) => OnRequestProgressStateUpdated?.Invoke(s));
                hubProxy.On<string, string>(Providers.StatusHubMessages.SendMsg, (a, b) => OnMessageFromService?.Invoke(a, b));

                _legacyConnection.Reconnecting += OnConnectionReconnecting;
                _legacyConnection.Reconnected += OnConnectionReconnected;
                _legacyConnection.Closed += OnConnectionClosed;

                await _legacyConnection.Start();

            }
            else
            {
                // newer signalr client/server

                // TODO: auth: https://docs.microsoft.com/en-us/aspnet/core/signalr/authn-and-authz?view=aspnetcore-3.1

                connection = new HubConnectionBuilder()
                .WithUrl(_statusHubUri)
                .WithAutomaticReconnect()
                .AddMessagePackProtocol()
                .Build();

                connection.Closed += async (error) =>
                {
                    await Task.Delay(new Random().Next(0, 5) * 1000);
                    await connection.StartAsync();
                };

                connection.On<RequestProgressState>(Providers.StatusHubMessages.SendProgressStateMsg, (s) =>
                {
                    OnRequestProgressStateUpdated?.Invoke(s);
                });

                connection.On<ManagedCertificate>(Providers.StatusHubMessages.SendManagedCertificateUpdateMsg, (u) =>
                {
                    OnManagedCertificateUpdated?.Invoke(u);
                });

                connection.On<string, string>(Providers.StatusHubMessages.SendMsg, (a, b) =>
                {
                    OnMessageFromService?.Invoke(a, b);
                });

                await connection.StartAsync();
            }
        }
        public async Task OnInitializedAsync()
        {
            _hubConnection = new HubConnectionBuilder().Build();

            _hubConnection.On <Message>("ReceiveMessage",
                                        (message) => {
                _messages.Add(message);
            });
            await _hubConnection.StartAsync();
        }
        /*
         * /// <summary>
         * /// Sends a new message to the server.
         * /// </summary>
         * /// <param name="Message">The message to be sent.</param>
         * public async System.Threading.Tasks.Task SendAsync(System.Text.Json.JsonElement Message) => await this.WSConnection.SendAsync("_mSended", Message);
         */

        #region Internal and Private Methods
        /// <summary>
        /// Configures the ClientWebSocket.
        /// </summary>
        /// <param name="Authorization">Authorization Header.</param>
        /// <returns>A task to be wait.</returns>
        /// <example>Basic YourBase64String</example>
        /// <example>Bearer YourAuthToken</example>
        async System.Threading.Tasks.Task SoftmakeAll.SDK.Fluent.Notifications.IClientWebSocket.ConfigureAsync(System.String Authorization)
        {
            if (System.String.IsNullOrWhiteSpace(Authorization))
            {
                return;
            }

            await this.DisposeAsync();

            this.WSConnection = new Microsoft.AspNetCore.SignalR.Client.HubConnectionBuilder()
                                .WithUrl(SoftmakeAll.SDK.Fluent.SDKContext.WebSocketBaseAddress, o =>
            {
                if (Authorization.StartsWith("Basic "))
                {
                    o.Headers.Add("Authorization", Authorization);
                }
                else
                {
                    o.AccessTokenProvider = () => System.Threading.Tasks.Task.FromResult(Authorization);
                }
            })
                                .WithAutomaticReconnect()
                                .Build();

            this.WSConnection.Closed       += this.WSConnection_Closed;
            this.WSConnection.Reconnecting += this.WSConnection_Reconnecting;
            this.WSConnection.Reconnected  += this.WSConnection_Reconnected;
            this.WSConnection.On <System.Text.Json.JsonElement>("_mReceived", Message =>
            {
                if (!(Message.IsValid()))
                {
                    return;
                }
                try { this.MessageReceived?.Invoke(null, Message); } catch { }
                try { this.OnMessageReceivedAction?.Invoke(Message); } catch { }
            });

            try
            {
                await this.WSConnection.StartAsync();

                await this.InvokeConnectionStateChangedEvents("Connected", null, null);
            }
            catch
            {
                await this.DisposeAsync();
            }
        }
Пример #5
0
        public HubClient(NavigationManager navigationManager)
        {
            var hubConnection = new HubConnectionBuilder()
                                .WithUrl(navigationManager.ToAbsoluteUri("/hub"))
                                .WithAutomaticReconnect()
                                .Build();

            _hub = hubConnection;

            _hub.Reconnected  += OnConnectionStateChanged;
            _hub.Closed       += InvokeConnectionStateChanged;
            _hub.Reconnecting += InvokeConnectionStateChanged;
            StartConnection();
            _hub.On <RoomMember>("JoinedRoom", async(arg) => await OnPeerJoinedRoom(arg));
            _hub.On <AnswerRequest>("SendAnswer", async(arg) => await OnAnswerReceived(arg));
            _hub.On <RTCIceCandidate, Guid>("NewIce", async(arg1, arg2) => await OnIceCandidate(arg1, arg2));
        }
 public static Task <ReadableChannel <TResult> > StreamAsync <TResult>(this HubConnection hubConnection, string methodName, object arg1, object arg2, object arg3, object arg4, object arg5, object arg6, object arg7, object arg8, object arg9, object arg10, CancellationToken cancellationToken = default)
 {
     return(hubConnection.StreamAsync <TResult>(methodName, new object[] { arg1, arg2, arg3, arg4, arg5, arg6, arg7, arg8, arg9, arg10 }, cancellationToken));
 }
 public static Task <ReadableChannel <TResult> > StreamAsync <TResult>(this HubConnection hubConnection, string methodName, object arg1, CancellationToken cancellationToken = default)
 {
     return(hubConnection.StreamAsync <TResult>(methodName, new object[] { arg1 }, cancellationToken));
 }
 public static Task <ReadableChannel <TResult> > StreamAsync <TResult>(this HubConnection hubConnection, string methodName, CancellationToken cancellationToken = default)
 {
     return(hubConnection.StreamAsync <TResult>(methodName, Array.Empty <object>(), cancellationToken));
 }
Пример #9
0
 public Streaming(CancellationToken cancellationToken, Type resultType, string invocationId, ILoggerFactory loggerFactory, HubConnection hubConnection)
     : base(cancellationToken, resultType, invocationId, loggerFactory.CreateLogger <Streaming>(), hubConnection)
 {
 }
 public static Task <TResult> InvokeAsync <TResult>(this HubConnection hubConnection, string methodName, CancellationToken cancellationToken = default(CancellationToken))
 {
     return(hubConnection.InvokeAsync <TResult>(methodName, Array.Empty <object>(), cancellationToken));
 }
Пример #11
0
 public static IAsyncEnumerable <TResult> StreamAsync <TResult>(this HubConnection hubConnection, string methodName, object arg1, object arg2, object arg3, CancellationToken cancellationToken = default)
 {
     return(hubConnection.StreamAsyncCore <TResult>(methodName, new[] { arg1, arg2, arg3 }, cancellationToken));
 }
Пример #12
0
 public static IAsyncEnumerable <TResult> StreamAsync <TResult>(this HubConnection hubConnection, string methodName, CancellationToken cancellationToken = default)
 {
     return(hubConnection.StreamAsyncCore <TResult>(methodName, Array.Empty <object>(), cancellationToken));
 }
Пример #13
0
 public HubBinder(HubConnection connection)
 {
     _connection = connection;
 }
 public static Task <TResult> InvokeAsync <TResult>(this HubConnection hubConnection, string methodName, object arg1, object arg2, object arg3, object arg4, object arg5, object arg6, object arg7, object arg8, object arg9, object arg10, CancellationToken cancellationToken = default(CancellationToken))
 {
     return(hubConnection.InvokeAsync <TResult>(methodName, new object[] { arg1, arg2, arg3, arg4, arg5, arg6, arg7, arg8, arg9, arg10 }, cancellationToken));
 }
 public static Task <TResult> InvokeAsync <TResult>(this HubConnection hubConnection, string methodName, object arg1, object arg2, CancellationToken cancellationToken = default(CancellationToken))
 {
     return(hubConnection.InvokeAsync <TResult>(methodName, new object[] { arg1, arg2 }, cancellationToken));
 }
Пример #16
0
        public async Task ConnectStatusStreamAsync()
        {
            if (_connectionConfig.ServerMode == "v1")
            {
                // older signalr client/server
                _legacyConnection             = new Microsoft.AspNet.SignalR.Client.HubConnection(_statusHubUri);
                _legacyConnection.Credentials = System.Net.CredentialCache.DefaultCredentials;

                var hubProxy = _legacyConnection.CreateHubProxy("StatusHub");

                hubProxy.On <ManagedCertificate>(Providers.StatusHubMessages.SendManagedCertificateUpdateMsg, (u) => OnManagedCertificateUpdated?.Invoke(u));
                hubProxy.On <RequestProgressState>(Providers.StatusHubMessages.SendProgressStateMsg, (s) => OnRequestProgressStateUpdated?.Invoke(s));
                hubProxy.On <string, string>(Providers.StatusHubMessages.SendMsg, (a, b) => OnMessageFromService?.Invoke(a, b));

                _legacyConnection.Reconnecting += OnConnectionReconnecting;
                _legacyConnection.Reconnected  += OnConnectionReconnected;
                _legacyConnection.Closed       += OnConnectionClosed;

                await _legacyConnection.Start();
            }
            else
            {
                // newer signalr client/server

                // TODO: auth: https://docs.microsoft.com/en-us/aspnet/core/signalr/authn-and-authz?view=aspnetcore-3.1

                connection = new HubConnectionBuilder()
                             .WithUrl(_statusHubUri, opts =>
                {
                    opts.HttpMessageHandlerFactory = (message) =>
                    {
                        if (message is System.Net.Http.HttpClientHandler clientHandler)
                        {
                            if (_connectionConfig.AllowUntrusted)
                            {
                                // allow invalid tls cert
                                clientHandler.ServerCertificateCustomValidationCallback +=
                                    (sender, certificate, chain, sslPolicyErrors) => { return(true); };
                            }
                        }
                        return(message);
                    };
                })
                             .WithAutomaticReconnect()
                             .AddMessagePackProtocol()
                             .Build();

                connection.Closed += async(error) =>
                {
                    await Task.Delay(new Random().Next(0, 5) * 1000);

                    await connection.StartAsync();
                };

                connection.On <RequestProgressState>(Providers.StatusHubMessages.SendProgressStateMsg, (s) =>
                {
                    OnRequestProgressStateUpdated?.Invoke(s);
                });

                connection.On <ManagedCertificate>(Providers.StatusHubMessages.SendManagedCertificateUpdateMsg, (u) =>
                {
                    OnManagedCertificateUpdated?.Invoke(u);
                });

                connection.On <string, string>(Providers.StatusHubMessages.SendMsg, (a, b) =>
                {
                    OnMessageFromService?.Invoke(a, b);
                });

                await connection.StartAsync();
            }
        }
Пример #17
0
        protected InvocationRequest(CancellationToken cancellationToken, Type resultType, string invocationId, ILogger logger, HubConnection hubConnection)
        {
            _cancellationTokenRegistration = cancellationToken.Register(self => ((InvocationRequest)self).Cancel(), this);

            InvocationId      = invocationId;
            CancellationToken = cancellationToken;
            ResultType        = resultType;
            Logger            = logger;
            HubConnection     = hubConnection;

            Log.InvocationCreated(Logger, InvocationId);
        }
Пример #18
0
        public static InvocationRequest Invoke(CancellationToken cancellationToken, Type resultType, string invocationId, ILoggerFactory loggerFactory, HubConnection hubConnection, out Task <object> result)
        {
            var req = new NonStreaming(cancellationToken, resultType, invocationId, loggerFactory, hubConnection);

            result = req.Result;
            return(req);
        }
 public static Task <TResult> InvokeAsync <TResult>(this HubConnection hubConnection, string methodName, object arg1, object arg2, object arg3, object arg4, object arg5, object arg6, CancellationToken cancellationToken = default)
 {
     return(hubConnection.InvokeCoreAsync <TResult>(methodName, new[] { arg1, arg2, arg3, arg4, arg5, arg6 }, cancellationToken));
 }