Ejemplo n.º 1
0
        private async Task <HubConnection> GetConnection()
        {
            var connection = new HubConnectionBuilder()
                             .WithUrl($"{_option.ApiUrl.ToString()}{JobQueueHubEndpoint}", options =>
            {
                options.AccessTokenProvider = () => Task.FromResult(_option.AuthorizationToken);
                options.CloseTimeout        = _option.ApiRequestTimeout;
            })
                             .Build();

            await connection.StartAsync();

            return(connection);
        }
Ejemplo n.º 2
0
        static async Task Main(string[] args)
        {
            Console.Write("Username: "******"Password: "******"";

            while (true)
            {
                var key = Console.ReadKey(intercept: true);
                if (key.Key == ConsoleKey.Enter)
                {
                    break;
                }
                password += key.KeyChar;
            }

            var hubConnection = new HubConnectionBuilder()
                                .WithUrl($"{baseUrl}/chat", options =>
            {
                options.AccessTokenProvider = async() =>
                {
                    var stringData = JsonConvert.SerializeObject(new
                    {
                        username,
                        password
                    });
                    var content = new StringContent(stringData);
                    content.Headers.ContentType = new MediaTypeHeaderValue("application/json");
                    var response = await httpClient.PostAsync($"{baseUrl}/api/token", content);
                    response.EnsureSuccessStatusCode();
                    return(await response.Content.ReadAsStringAsync());
                };
            })
                                .Build();

            hubConnection.On <string, string>("newMessage",
                                              (sender, message) => Console.WriteLine($"{sender}: {message}"));

            await hubConnection.StartAsync();

            System.Console.WriteLine("\nConnected!");

            while (true)
            {
                var message = Console.ReadLine();
                await hubConnection.SendAsync("SendMessage", message);
            }
        }
Ejemplo n.º 3
0
        private async Task ServerClosesConnectionWithErrorIfHubCannotBeCreated(TransportType transportType)
        {
            using (StartLog(out var loggerFactory, testName: $"ConnectionCanSendAndReceiveMessages_{transportType.ToString()}"))
            {
                var logger = loggerFactory.CreateLogger <EndToEndTests>();

                var url = _serverFixture.BaseUrl + "/uncreatable";

                var connection = new HubConnectionBuilder()
                                 .WithUrl(new Uri(url))
                                 .WithTransport(transportType)
                                 .WithLoggerFactory(loggerFactory)
                                 .Build();
                try
                {
                    var closeTcs = new TaskCompletionSource <object>();

                    connection.Closed += e =>
                    {
                        logger.LogInformation("Connection closed");
                        if (e != null)
                        {
                            closeTcs.TrySetException(e);
                        }
                        else
                        {
                            closeTcs.TrySetResult(null);
                        }
                        return(Task.CompletedTask);
                    };

                    logger.LogInformation("Starting connection to {url}", url);
                    await connection.StartAsync().OrTimeout();

                    await closeTcs.Task.OrTimeout();
                }
                catch (Exception ex)
                {
                    logger.LogInformation(ex, "Test threw exception");
                    throw;
                }
                finally
                {
                    logger.LogInformation("Disposing Connection");
                    await connection.DisposeAsync().OrTimeout();

                    logger.LogInformation("Disposed Connection");
                }
            }
        }
Ejemplo n.º 4
0
        static async Task Main(string[] args)
        {
            var connection = new HubConnectionBuilder().WithUrl("https://localhost:5001/chat")
                             .WithAutomaticReconnect()
                             .AddJsonProtocol().Build();

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

                await connection.StartAsync();
            };

            connection.On <string, string>("inMessage", (name, text) =>
            {
                Console.WriteLine($"{name}: {text}");
            });

            connection.On <string>("aggregation", (aggregation) =>
            {
                Console.WriteLine(aggregation);
            });

            await connection.StartAsync();

            while (true)
            {
                var line = Console.ReadLine();
                if (line == "q")
                {
                    break;
                }

                await connection.SendAsync("Send", "Console", line, "1");
            }
            await connection.StopAsync();
        }
Ejemplo n.º 5
0
        static async Task Main(string[] args)
        {
            var accessToken = "{generate the access token}";
            var hubName     = "chat";
            var endpoint    = "{the endpoint from the connection string}/client/";
            var connection  = new HubConnectionBuilder().WithUrl(
                $"wss://{endpoint}?hub={hubName}&asrs.op=%2F{hubName}"
                , HttpTransportType.WebSockets,
                s =>
            {
                s.AccessTokenProvider = () => Task.FromResult(accessToken);
                s.SkipNegotiation     = true;
            }
                ).ConfigureLogging(logging =>
            {
                logging.AddConsole();
                logging.SetMinimumLevel(LogLevel.Debug);
            })
                              .Build();

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

                await connection.StartAsync();
            };

            connection.On <string, string>("broadcastMessage", (name, message) =>
            {
                Console.WriteLine(name + ":" + message);
            });

            await connection.StartAsync();

            Console.ReadKey();
        }
Ejemplo n.º 6
0
        static async Task Main(string[] args)
        {
            Console.BackgroundColor = ConsoleColor.Blue;
            Console.ForegroundColor = ConsoleColor.White;

            Console.WriteLine("Signal-R Sender!");

            const string url = "http://localhost:5000/hubs/sensors";

            // dotnet add package Microsoft.AspNetCore.SignalR.Client

            HubConnection connection = new HubConnectionBuilder()
                                       .WithUrl(url)
                                       .Build();

            System.Console.WriteLine("Connecting...");
            await connection.StartAsync();

            System.Console.WriteLine("Connected.");


            while (true)
            {
                // dotnet add package Bogus
                var faker = new Faker <Measure>()
                            .RuleFor(p => p.DeviceId, "temp-001")
                            .RuleFor(p => p.Temperature, f => f.Random.Float(20, 40));

                Measure measure = faker.Generate();


                // Measure measure = new Measure
                // {
                //     DeviceId = "temp-001",
                //     Temperature = 26.04f
                // };

                await connection.SendAsync("MeasureAdded", measure);

                System.Console.WriteLine($"Sent {measure.Temperature}");

                await Task.Delay(TimeSpan.FromSeconds(1));
            }

            System.Console.WriteLine("Press enter key to exit.");
            Console.ReadLine();

            Console.ResetColor();
        }
Ejemplo n.º 7
0
        protected override async Task ExecuteAsync(CancellationToken stoppingToken)
        {
            HubConnection hubConnection = new HubConnectionBuilder().WithUrl($"{Configuration["ApiBase"]}/hub").Build();

            hubConnection.On <ServiceConfig>("AddServerConfig", x =>
            {
                _logger.LogInformation("Adding {service}", x.ServiceName);
                services.Add(x);
            });
            hubConnection.On <ServiceConfig>("RemoveService", x =>
            {
                _logger.LogInformation("Removing {service}", x.ServiceName);
                services.RemoveAt(services.FindIndex(0, s => s.ServiceName == x.ServiceName));
            });
            await hubConnection.StartAsync();

            await hubConnection.SendAsync("RegisterServer", Environment.MachineName);

            int interval = await service.GetInterval();

            services = await service.GetServices(Environment.MachineName);

            if (interval == 0)
            {
                interval = 1;
            }
            while (!stoppingToken.IsCancellationRequested)
            {
                _logger.LogInformation("Checking {count} service(s)", services.Count);
                Parallel.ForEach(services, async item =>
                {
                    try
                    {
                        _logger.LogInformation("Checking service {name}", item.ServiceName);
                        using var ps = PowerShell.Create();

                        var results = ps.AddScript($"get-service {item.ServiceName} ").Invoke();
                        foreach (var result in results)
                        {
                            var isRunning = result.Properties["Status"].Value.ToString() == "Running";
                            await service.UpdateStatus(item.Id, isRunning ? "Up" : "Down");
                            _logger.LogInformation("Service {name} is {status}", item.ServiceName, isRunning ? "Up" : "Down");
                        }
                    }
                    catch (Exception ex) { _logger.LogError("Error", ex); }
                });
                await Task.Delay(TimeSpan.FromMinutes(interval), stoppingToken);
            }
        }
Ejemplo n.º 8
0
        private async Task SetupSignalR()
        {
            var uri           = new Uri($"{_config[Constants.CONFIG_SIGNALR_URI]}");
            var hubConnection = new HubConnectionBuilder()
                                .WithAutomaticReconnect()
                                .WithUrl(uri)
                                .Build();

            hubConnection.On <ChannelActivityEntity>("UpdateChannelState", async entity =>
            {
                var activity = (StreamActivity)Enum.Parse(typeof(StreamActivity), entity.Activity);
                switch (activity)
                {
                case StreamActivity.StreamStarted:
                    await Start(entity.PartitionKey);
                    break;

                case StreamActivity.StreamStopped:
                    await Stop(entity.PartitionKey);
                    break;

                case StreamActivity.MessagePosted:
                    break;

                case StreamActivity.UserJoined:
                    break;

                case StreamActivity.UserLeft:
                    break;

                case StreamActivity.UserFollowed:
                    break;

                case StreamActivity.UserSubscribed:
                    break;

                case StreamActivity.ViewerTimestamped:
                    break;

                default:
                    throw new ArgumentOutOfRangeException();
                }
            });

            hubConnection.On <string>("UpdatePassword", async passwordText => { await UpdatePassword(passwordText); });
            await hubConnection.StartAsync().ConfigureAwait(false);

            _logger.LogInformation($"{DateTime.UtcNow.ToString(CultureInfo.CurrentUICulture)}: Connected to SignalR hub {uri} - {hubConnection.ConnectionId}");
        }
        private static async Task Main(string[] args)
        {
            //HubConnectionオブジェクトを使ってサーバーのSignalRハブと通信する
            HubConnection connection;

            //SignalRハブとの通信を担うオブジェクトを生成
            connection = new HubConnectionBuilder()
                         .WithUrl("https://localhost:44304/mysignalrhub")
                         .WithAutomaticReconnect()
                         .Build();

            //クライアント側の受信時の処理を行うメソッドを登録する。
            //文字列で指定した名前でサーバー側から呼び出される。
            connection.On <string>("ReceiveMessage", (string messageFromServer) =>
            {
                Console.WriteLine($"サーバーから{DateTimeOffset.Now.ToString("yyyy/MM/dd/HH:mm:ss.fff")}に受信:\n {messageFromServer}");
            });

            try
            {
                //サーバー側のSignalRハブと接続
                await connection.StartAsync();

                Console.WriteLine("接続できました");
            }
            catch (Exception ex)
            {
                Console.WriteLine("接続できませんでした");
            }

            while (true)
            {
                Console.Write("メッセージを入力: ");

                string input = Console.ReadLine();

                try
                {
                    //メッセージ送信
                    await connection.InvokeAsync <string>("SendToAllAsync", input);
                }
                catch (Exception ex)
                {
                    Console.WriteLine("メッセージの送信に失敗しました");
                }

                Thread.Sleep(500);
            }
        }
Ejemplo n.º 10
0
        static async Task Main(string[] args)
        {
            Console.WriteLine("Hello World!");
            HubConnection connection = new HubConnectionBuilder()
                                       .WithUrl("http://localhost:5001/notification")
                                       .Build();

            connection.On <string>("HandleNotification", (message) =>
            {
                Console.WriteLine(message);
            });
            await connection.StartAsync();

            Console.ReadKey();
        }
Ejemplo n.º 11
0
        private static async Task Listen()
        {
            var connection = new HubConnectionBuilder()
                             .WithUrl("http://localhost:56428/chat")
                             .Build();

            connection.On <string>("broadcast", (message) =>
            {
                Console.WriteLine(message);
            });

            await connection.StartAsync();

            Console.WriteLine("Listening...");
        }
Ejemplo n.º 12
0
        static async Task Main(string[] args)
        {
            var connection = new HubConnectionBuilder()
                             .WithUrl("http://localhost:5000/chatHub")
                             .Build();

            connection.On <string, string>("ReceiveMessage", (user, message) =>
            {
                Console.WriteLine($"{user} says {message}");
            });

            await connection.StartAsync();

            Console.ReadKey();
        }
Ejemplo n.º 13
0
        public Launcher()
        {
            _queues = new List <BufferBlock <string> >();

            _cancellationTokenSource = new CancellationTokenSource();
            _tasks = new List <Task>();

            var connection = new HubConnectionBuilder()
                             .WithUrl("http://localhost:5000/hub")
                             .Build();

            connection.On <string>("message", HandleMessage);

            connection.StartAsync().Wait();
        }
Ejemplo n.º 14
0
        public async Task <IActionResult> Get()
        {
            var connection = new HubConnectionBuilder()
                             .WithUrl("wss://localhost:44302/readvalues").Build();

            connection.On("test", (string deviceId, string value) =>
            {
                Console.WriteLine(deviceId, value);
            });
            await connection.StartAsync();

            await connection.InvokeAsync("SendMessage", "test", "hello from server");

            return(Ok());
        }
Ejemplo n.º 15
0
        protected override async Task OnInitializedAsync()
        {
            await LoadDataAsync();

            hubConnection = new HubConnectionBuilder()
                            .WithUrl(_navigationManager.ToAbsoluteUri("/signalRHub"))
                            .WithUrl(_navigationManager.ToAbsoluteUri("/signalRHub"))
                            .Build();
            hubConnection.On("UpdateDashboard", async() =>
            {
                await LoadDataAsync();
                StateHasChanged();
            });
            await hubConnection.StartAsync();
        }
Ejemplo n.º 16
0
        public async Task Run()
        {
            WriteLine("Press any key to exit.");
            var connection = new HubConnectionBuilder()
                             .WithUrl(Endpoint).Build();

            connection.On <BuildingActionSnaphotDto>("SendBuildingState", buildingSnapshot =>
            {
                WriteLine("Received message");
                WriteLine(JsonSerializer.Serialize(buildingSnapshot));
            });
            await connection.StartAsync().ConfigureAwait(false);

            ReadLine();
        }
Ejemplo n.º 17
0
        private async Task _SignalRHelper_HubReceiverContainer_Gets_From_Server()
        {
            var hc = new HubConnectionBuilder()
                     .WithUrl(ProxyTestHostHolder._mainHubString).Build();
            await hc.StartAsync();

            var client = HubProxyBuilder.CreateProxy <IBar>(hc);
            var hubRec = new HubReceiverContainer <IFoo>(hc, new FooImpl());
            await client.StringType("hello");

            SpinWait.SpinUntil(() => false, TimeSpan.FromSeconds(2));
            Assert.True(FooImpl.callCounter["hello"] > 0);
            GC.KeepAlive(hubRec);
            hubRec.Dispose();
        }
Ejemplo n.º 18
0
        public async Task AlwaysSendAttribute_Is_Respected()
        {
            var hc = new HubConnectionBuilder()
                     .WithUrl(ProxyTestHostHolder._mainHubString).Build();
            await hc.StartAsync();

            var client = HubProxyBuilder.CreateProxy <IBar>(hc, true);
            await client.StreamToServerSend(clientStreamData(), "asend");

            Assert.Throws <KeyNotFoundException>(() =>
                                                 GroupHub.streamCounter["asend"].Count);
            await Task.Delay(TimeSpan.FromSeconds(5));

            Assert.Equal(5, GroupHub.streamCounter["asend"].Count);
        }
        public void BuildServerConnection()
        {
            HubConnection connection = new HubConnectionBuilder()
                                       .WithUrl("http://localhost:5000/marketDataHub")
                                       .WithAutomaticReconnect() //handel lost connection
                                       .Build();

            Logger.LogInformation("Main thread ID" + Thread.CurrentThread.ManagedThreadId);

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

                await connection.StartAsync();
            };

            connection.Reconnecting += error =>
            {
                Debug.Assert(connection.State == HubConnectionState.Reconnecting);
                Logger.LogInformation("Connection lost, trying to reconnect");
                return(Task.CompletedTask);
            };

            connection.Reconnected += connectionId =>
            {
                Debug.Assert(connection.State == HubConnectionState.Connected);
                return(Task.CompletedTask);
            };

            //on market data notification received
            connection.On <List <MarketDataModelPresenter> >("PublishMarketDataList", (data) => UpdateStockGrid(data));

            //Open client server connection
            connection.StartAsync();
        }
        public async Task StartToListen()
        {
            var _connection = new HubConnectionBuilder()
                              .WithUrl("http://localhost:64480/sensorshub")
                              .Build();

            _connection.On <SensorDataDto>("SensorData", sensorData =>
            {
                Console.WriteLine($"New SensorData received (id: {sensorData.Id})");

                _sensorDataProducer.Produce(sensorData);
            });

            await _connection.StartAsync();
        }
Ejemplo n.º 21
0
        private async Task ConfigurarSignalR(ObservableCollection <Promocao> promocoes)
        {
            var connection = new HubConnectionBuilder()
                             .WithAutomaticReconnect()
                             .WithUrl("https://realpromoapiwebabb.azurewebsites.net/PromoHub").Build();

            connection.On <Promocao>("receberPromocao", (promocao) =>
            {
                Xamarin.Forms.Device.InvokeOnMainThreadAsync(() => {
                    promocoes.Add(promocao);
                });
            });

            await connection.StartAsync();
        }
Ejemplo n.º 22
0
        static async Task Main(string[] args)
        {
            Console.WriteLine("Hello World!");

            HubConnection connection = new HubConnectionBuilder()
                                       .WithUrl("http://localhost:18128/ChatHub")
                                       .WithAutomaticReconnect()
                                       .Build();

            await connection.StartAsync();

            string message = Console.ReadLine();

            await connection.InvokeAsync("SendMessage", "Agent", message);
        }
Ejemplo n.º 23
0
        internal static IServiceCollection AddSignalRConnection(this IServiceCollection services, string hubUrl)
        {
            HubConnection connection = new HubConnectionBuilder()
                                       .WithUrl(hubUrl)
                                       .Build();

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

                await connection.StartAsync();
            };

            connection.On <string>("OnEvent", message => {
                // TODO: message processing here
                Console.WriteLine(message);
            });

            connection.StartAsync();

            services.AddSingleton <HubConnection>(connection);
            return(services);
        }
Ejemplo n.º 24
0
        /// <summary>
        /// TO DO : Client should be able to subscribe the ohlc data by passing stock name
        /// Currently and empty string is passed. This will perform ohlc analysis on all the feed.
        /// </summary>
        /// <param name="args"></param>
        static void Main(string[] args)
        {
            var connection = new HubConnectionBuilder()
                             .WithUrl("http://localhost:5000/ohlchub")
                             .Build();

            connection.StartAsync().Wait();
            connection.InvokeCoreAsync("SendMessage", args: new[] { "subscribe", "", "15" });
            connection.On("ReceiveMessage", (string eventname, string stockname) =>
            {
                Console.WriteLine("Running Analyzer on Server " + stockname);
            });

            Console.ReadLine();
        }
Ejemplo n.º 25
0
        public async Task <JoinResponse> Connect(int meetingId)
        {
            MeetingId  = meetingId;
            Connection = new HubConnectionBuilder()
                         .WithUrl("http://192.168.0.73:5000/game",
                                  options => { options.Headers.Add("Authorization", $"Bearer {_token.Token}"); })
                         .Build();
            await Connection.StartAsync();

            Connection.On <ClientResponse>("TaskChange", OnTaskChanged);
            Connection.On <OrganizerResponse>("Submitted", OnSubmitted);
            Connection.On("CloseWindow", OnCLoseWindow);

            return(await Connection.InvokeAsync <JoinResponse>("join", MeetingId));
        }
Ejemplo n.º 26
0
        /// <summary>
        /// Open connection
        /// </summary>
        /// <returns></returns>
        private async Task <HubConnection> OpenAsync()
        {
            var connection = new HubConnectionBuilder()
                             .WithAutomaticReconnect()
                             .AddNewtonsoftJsonProtocol(options => {
                options.PayloadSerializerSettings = JsonConvertEx.GetSettings();
            })
                             .WithUrl(_endpointUri)
                             .Build();

            connection.Closed += ex => OnClosedAsync(connection, ex);
            await connection.StartAsync();

            return(connection);
        }
Ejemplo n.º 27
0
        private static async Task <HubConnection> Connect(string endpoint)
        {
            var connection = new HubConnectionBuilder()
                             .WithUrl(endpoint)
                             .AddNewtonsoftJsonProtocol(s => s.PayloadSerializerSettings.ConfigureRemoteLinq())
                             .Build();

            while (connection.State == HubConnectionState.Disconnected) // Wait for server to start
            {
                try { await connection.StartAsync(); }
                catch (HttpRequestException ex) { Console.WriteLine("Error connecting to server: " + ex.Message); }
            }

            return(connection);
        }
Ejemplo n.º 28
0
        // <= C# 7.0
        // static void Main(string[] args) => MainAsync(args).GetAwaiter().GetResult();

        // dotnet add package Microsoft.AspNetCore.SignalR.Client
        static async Task Main(string[] args)
        {
            Console.BackgroundColor = ConsoleColor.Green;
            Console.ForegroundColor = ConsoleColor.White;
            Console.WriteLine("Hello Signal-R Sender!");

            const string url = "http://localhost:5000/signalr/chatter";

            HubConnection connection = new HubConnectionBuilder()
                                       .WithUrl(url)
                                       .Build();

            Console.WriteLine("connecting...");

            await connection.StartAsync();

            Console.WriteLine("Connected.");

            //while(true)
            //{
            //    Console.Write("Type message: ");
            //    string content = Console.ReadLine();

            //    ChatMessage message = new ChatMessage { Content = content };

            //    await connection.SendAsync("SendMessage", message, "Klon");
            //}

            Stopwatch stopwatch = new Stopwatch();

            stopwatch.Start();

            for (int i = 0; i < 10000; i++)
            {
                ChatMessage message = new ChatMessage {
                    Content = $"Temp {i}"
                };

                await connection.SendAsync("SendMessage", message, "Klon");
            }

            stopwatch.Stop();
            Console.WriteLine($"elapsed time: {stopwatch.Elapsed}");

            Console.ReadKey();

            Console.ResetColor();
        }
Ejemplo n.º 29
0
        private static async Task WaitingForMessage(string[] args)
        {
            //HubConnection connection;
            HttpClient client = new HttpClient();

            client.BaseAddress = new Uri("https://netconfbcn2019demo2publishtosignalr.azurewebsites.net");
            HttpResponseMessage response = await client.GetAsync("/api/negotiatevotingresults");

            response.EnsureSuccessStatusCode();
            var content = JsonConvert.DeserializeObject <NegotiateResponse>(await response.Content.ReadAsStringAsync());

            string token = content.Accesstoken;
            string url   = content.Url;

            var connection = new HubConnectionBuilder()
                             .WithUrl(url, options => {
                options.AccessTokenProvider = () => Task.FromResult(token);
            })
                             .Build();

            connection.StartAsync().ContinueWith(task => {
                if (task.IsFaulted)
                {
                    Console.WriteLine("Se ha producido un error al establecer la conexión: {0}",
                                      task.Exception.GetBaseException());
                }
                else
                {
                    Console.WriteLine("Connected");

                    connection.On <string>("VotingResults", (resultados) => {
                        Console.WriteLine($"{resultados}");
                    });

                    while (true)
                    {
                        string message = Console.ReadLine();

                        if (string.IsNullOrEmpty(message))
                        {
                            break;
                        }
                    }
                }
            }).Wait();

            await connection.StopAsync();
        }
Ejemplo n.º 30
0
        private async Task <HubConnection> SetUpHubConnection(ConnectionString connectionString, string hubUrl, string nameIdentifier)
        {
            var accessTokensService = new AccessTokensService();
            var accessToken         = accessTokensService.GenerateAccessToken(connectionString, hubUrl, nameIdentifier);

            var hubConnection = new HubConnectionBuilder()
                                .WithUrl(hubUrl, options =>
            {
                options.AccessTokenProvider = () => Task.FromResult(accessToken);
            })
                                .Build();

            await hubConnection.StartAsync();

            return(hubConnection);
        }