Esempio n. 1
0
        static async Task Main(string[] args)
        {
            var connection = new HubConnectionBuilder()
                             .WithUrl("https://localhost:5001/Chat")
                             .Build();

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

                // await connection.StartAsync();
            };

            await connection.StartAsync();

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

            while (true)
            {
                var key = Console.ReadKey();
                if (key.Key == ConsoleKey.S)
                {
                    await connection.SendAsync("SendMessage", "console", "hello from console");
                }
                else
                {
                    await connection.StopAsync();
                }
            }
        }
        private async Task TheTask()
        {
            while (_started)
            {
                try
                {
                    var hubConnection = new HubConnectionBuilder()
                                        .WithUrl(_signalRurl)
                                        .Build();

                    await StartAsync(hubConnection);

                    _currentConnection.Set(hubConnection);

                    await SubscribeAsync(hubConnection);
                    await PingProcessAsync(hubConnection);

                    await hubConnection.StopAsync();

                    _currentConnection.Set(null);

                    ResponseAsAllRequestsAreDisconnected();
                }
                catch (Exception e)
                {
                    Console.WriteLine("TheTask:" + e);
                }
            }
        }
Esempio n. 3
0
        public async Task SendGreeting___clients_notified()
        {
            using TestServer testServer = _factory.Server;

            var connection = new HubConnectionBuilder()
                             .WithUrl(
                testServer.BaseAddress + GreetingHub.HubUrl,
                opts => opts.HttpMessageHandlerFactory = _ => testServer.CreateHandler())
                             .Build();

            string actualName    = null;
            string actualMessage = null;

            connection.On <string, string>(nameof(IGreetingClient.NewGreeting), (name, msg)
                                           => (actualName, actualMessage) = (name, msg));

            await connection.StartAsync();

            const string name    = "Batman";
            const string message = "Hi from Batman";

            // "Act" must be done this way, as with `new GreetingHub` no clients will be available --> NullRefException
            await connection.InvokeAsync(nameof(GreetingHub.SendGreeting), name, message);

            await connection.StopAsync();

            Assert.Multiple(() =>
            {
                Assert.AreEqual(name, actualName);
                Assert.AreEqual(message, actualMessage);
            });
        }
Esempio n. 4
0
        private static void Main(string[] args)
        {
            var Connection = new HubConnectionBuilder()
                             .WithUrl("http://localhost:44343/Informacije")
                             .Build();

            Connection.StartAsync().ContinueWith(task => {
                if (task.IsFaulted)
                {
                    Console.WriteLine("There was an error opening the connection:{0}",
                                      task.Exception.GetBaseException());
                }
                else
                {
                    Console.WriteLine("Connected");
                }
            }).Wait();

            Connection.On <string>("ReciveInfo", obj => {
                var deserializedObj = JsonConvert.DeserializeObject <InfoModel>(obj);
                Console.WriteLine(deserializedObj.ToString());
            });



            Console.Read();
            Connection.StopAsync().Wait();
        }
Esempio n. 5
0
        public async Task GetDesignToSend(int id)
        {
            var design = await GetDesign(id);

            if (design == null)
            {
                design = await GetDesign(2);
            }

            string designCoords = design.DesignCoords;

            var url = "https://liteberrypiserver.azurewebsites.net/raspberrypi";

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

            var t = connection.StartAsync();

            t.Wait();
            // send a message to the hub
            await connection.InvokeAsync("SendLiteBerry", designCoords);

            await connection.StopAsync();

            //close the connection
            //t.Dispose();
        }
        static async Task Main(string[] args)
        {
            var url = "https://workshop.ursatile.com:5001/chatHub";

            Console.WriteLine("Connecting to SignalR...");
            var connection = new HubConnectionBuilder().WithUrl(url).Build();

            connection.On <string, string>("ReceiveMessage", (s1, s2) => ReceiveMessage(s1, s2));
            await connection.StartAsync();

            Console.WriteLine($"Connected to SignalR at {url}");
            Console.Write("Enter your name: ");
            var name = Console.ReadLine();

            while (true)
            {
                var message = Console.ReadLine();
                if (name == "quit")
                {
                    break;
                }
                await connection.SendAsync("SendMessage", name, message);
            }
            await connection.StopAsync();
        }
Esempio n. 7
0
        private static async Task Main(string[] args)
        {
            Console.CancelKeyPress += OnConsole_CancelKeyPressed;

            const string address    = "http://localhost:5000/information";
            var          connection = new HubConnectionBuilder()
                                      .WithUrl(address)
                                      .Build();

            connection.On("ClientConnected", OnClientConnected);
            connection.On("ClientDisconnected", OnClientDisconnected);
            connection.On <DateTime, string>("IntroduceNewClient", OnIntroduceNewClient);
            connection.On <DateTime, string, string>("ClientMessage", ReceiveMessage);

            Console.Write("User name >");
            var user_name = Console.ReadLine();

            Console.WriteLine();

            await connection.StartAsync();

            await connection.SendAsync("IntroduceClient", user_name);

            while (!__ReadLineCancellation.IsCancellationRequested)
            {
                var message = await Task.Run(Console.ReadLine).WithCancellation(__ReadLineCancellation.Token);

                await connection.InvokeAsync("ServerMessage", user_name, message);
            }

            await connection.StopAsync();
        }
Esempio n. 8
0
        static async Task Main(string[] args)
        {
            //Use your signalr app url here
            var connection = new HubConnectionBuilder()
                             .WithUrl("https://localhost:44391/messagehub")
                             .Build();

            connection.On <string, string>("SRMessage", (sender, message) => {
                Console.WriteLine($"{sender} says {message}");
            });
            await connection.StartAsync();

            await connection.InvokeAsync("SendMessage", $"C# Client", "C# Client Started..").ContinueWith(task =>
            {
                if (task.IsFaulted)
                {
                    Console.WriteLine("There was an error calling send: {0}",
                                      task.Exception.GetBaseException());
                }
                else
                {
                    Console.WriteLine(task.Status);
                }
            });

            Console.Read();
            await connection.StopAsync();
        }
Esempio n. 9
0
        static async Task Main()
        {
            var builder = new ConfigurationBuilder()
                          .SetBasePath(Directory.GetCurrentDirectory())
                          .AddJsonFile("appsettings.json");

            var configuration = builder.Build();

            _settings    = configuration.GetSection("FunApi").Get <Settings>();
            _mediaPlayer = new VlcMediaPlayer(_settings);

            var connection = new HubConnectionBuilder()
                             .WithUrl(new Uri($"{_settings.ServerAddress}/videohub"))
                             .WithAutomaticReconnect()
                             .Build();

            await connection.StartAsync();

            Console.WriteLine($"Connected to {_settings.ServerAddress}");

            connection.On <string>("PlayVideo", PlayVideo);
            connection.On("StopVideo", StopVideo);

            Console.WriteLine("Press any key to exit");

            Console.ReadKey();

            await connection.StopAsync();

            Console.WriteLine("Connection closed");
        }
Esempio n. 10
0
        private static async Task Main(string[] args)
        {
            /* TODO: Replace this url with config. */
            var url = "https://localhost:44390/runnerhub";

            var connection = new HubConnectionBuilder()
                             .WithUrl($"{url}")
                             .WithAutomaticReconnect()
                             .Build();

            var botService = new BotService();

            await connection.StartAsync().ContinueWith(task =>
            {
                /* Clients should disconnect from the server when the server sends the request to do so. */
                connection.On <Guid>("Disconnect", (Id) =>
                {
                    Console.WriteLine("Disconnected:");

                    connection.StopAsync();
                });

                /* Get the current WorldState along with the last known state of the current client. */
                connection.On <GameState, GameObject>("ReceiveGameState", (gameState, bot) =>
                {
                    Console.WriteLine("Current ConnectionId: " + bot.Id);

                    botService.SetBot(bot);
                    botService.SetGameState(gameState);

                    foreach (var _bot in gameState.GameObjects.Where(o => o.ObjectType == ObjectTypes.Player))
                    {
                        Console.WriteLine(String.Format("Id - {0}, PositionX - {1}, PositionY - {2}, Size - {3}", _bot.Id, _bot.Position.X, _bot.Position.Y, _bot.Size));
                    }
                });

                while (true)
                {
                    /* This sleep is important to sync the two calls below. */
                    Thread.Sleep(1000);

                    var bot = botService.GetBot();

                    if (bot == null)
                    {
                        return;
                    }

                    connection.InvokeAsync("RequestGameState");

                    /* TODO: Add bot logic here between RequestWorldState and SendClientAction, use SetClient to form object to be sent to Runner. */
                    botService.SetPlayerAction(botService.GetPlayerAction());

                    connection.InvokeAsync("SendPlayerAction", botService.GetPlayerAction());
                }
            });
        }
        public async Task Consume(ConsumeContext <IReportEvent> context)
        {
            Console.WriteLine($"{context.Message.ReportName} isimli ürün yayınlanarak müşteriler bilgilendirilmiştir.");
            HubConnection connection = new HubConnectionBuilder().WithUrl("https://localhost:44300/UIHub").Build();
            await connection.StartAsync();

            await connection.InvokeAsync("SendMessageAsync", context.Message);

            await connection.StopAsync();
        }
Esempio n. 12
0
        static async Task running()
        {
            var connection = new HubConnectionBuilder().WithUrl("https://localhost:44357/chathub").Build();
            await connection.StartAsync();

            Console.WriteLine("client connection state:" + connection.State);
            await connection.StopAsync();

            await connection.DisposeAsync();
        }
Esempio n. 13
0
        public async Task HandlerClientAsync(ConnectionContext client)
        {
            HubConnection connection = new HubConnectionBuilder()
                                       .WithUrl(new Uri("http://zwovo.xyz:5000/chathub"))
                                       .Build();


            connection.On <byte[]>("recv", async(msg) =>
            {
                await client.Transport.Output.WriteAsync(msg);
            });

            await connection.StartAsync();

            try
            {
                //注册
                await connection.InvokeAsync("Regist", "1");

                while (true)
                {
                    //接受
                    var readResult = await client.Transport.Input.ReadAsync();

                    if (readResult.Buffer.IsEmpty)
                    {
                        break;
                    }

                    SequencePosition position = readResult.Buffer.Start;
                    if (readResult.Buffer.TryGet(ref position, out ReadOnlyMemory <byte> memory))
                    {
                        //发送到中心
                        await connection.InvokeAsync("SendMessage", "2", memory.ToArray());

                        client.Transport.Input.AdvanceTo(readResult.Buffer.GetPosition(memory.Length));
                    }

                    if (readResult.IsCompleted || readResult.IsCanceled)
                    {
                        break;
                    }
                }
            }
            catch (Exception ex)
            {
                Console.WriteLine(ex.Message);
            }
            finally
            {
                await connection.StopAsync();

                await client.Transport.Input.CompleteAsync();
            }
        }
Esempio n. 14
0
        private static void Main(string[] args)
        {
            HubConnection connection = new HubConnectionBuilder()
                                       .WithUrl("http://localhost:8080/consolehub")
                                       .Build();

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

            try
            {
                connection.StartAsync().Wait();
            }
            catch (Exception ex)
            {
                Console.WriteLine(ex);
            }

            Console.WriteLine("SimpleParamTest:");
            SimpleParamTest(connection);

            // Console.WriteLine("ObjParamTest:");
            // ObjParamTest(connection);

            // Console.WriteLine("ObjParamWithArrayTest:");
            // ObjParamWithArrayTest(connection);

            // Console.WriteLine("ObjParamWithListTest:");
            // ObjParamWithListTest(connection);

            // Console.WriteLine("ObjParamWithResultTest:");
            // ObjParamWithResultTest(connection);

            // Console.WriteLine("ObjParamWithArrayWithResultTest:");
            // ObjParamWithArrayWithResultTest(connection);

            // Console.WriteLine("ObjParamWithListWithResultTest:");
            // ObjParamWithListWithResultTest(connection);

            try
            {
                connection.StopAsync().Wait();
            }
            catch (Exception ex)
            {
                Console.WriteLine(ex);
            }

            Console.ReadLine();
        }
Esempio n. 15
0
        public async Task Connect()
        {
            ConnectionInfo = ConfigService.GetConnectionInfo();

            HubConnection = new HubConnectionBuilder()
                            .WithUrl(ConnectionInfo.Host + "/DeviceHub")
                            .Build();

            RegisterMessageHandlers();

            await HubConnection.StartAsync();

            var device = await DeviceInformation.Create(ConnectionInfo.DeviceID, ConnectionInfo.OrganizationID);

            var result = await HubConnection.InvokeAsync <bool>("DeviceCameOnline", device);

            if (!result)
            {
                // Orgnanization ID wasn't found, or this device is already connected.
                // The above can be caused by temporary issues on the server.  So we'll do
                // nothing here and wait for it to get resolved.
                Logger.Write("There was an issue registering with the server.  The server might be undergoing maintenance, or the supplied organization ID might be incorrect.");
                await Task.Delay(TimeSpan.FromMinutes(1));

                await HubConnection.StopAsync();

                return;
            }

            if (string.IsNullOrWhiteSpace(ConnectionInfo.ServerVerificationToken))
            {
                IsServerVerified = true;
                ConnectionInfo.ServerVerificationToken = Guid.NewGuid().ToString();
                await HubConnection.InvokeAsync("SetServerVerificationToken", ConnectionInfo.ServerVerificationToken);

                ConfigService.SaveConnectionInfo(ConnectionInfo);
            }
            else
            {
                await HubConnection.InvokeAsync("SendServerVerificationToken");
            }

            if (ConfigService.TryGetDeviceSetupOptions(out DeviceSetupOptions options))
            {
                await HubConnection.InvokeAsync("DeviceSetupOptions", options, ConnectionInfo.DeviceID);
            }

            HeartbeatTimer?.Dispose();
            HeartbeatTimer          = new Timer(TimeSpan.FromMinutes(5).TotalMilliseconds);
            HeartbeatTimer.Elapsed += HeartbeatTimer_Elapsed;
            HeartbeatTimer.Start();
        }
Esempio n. 16
0
        public async Task SignalRConnectDisconnect()
        {
            var connection = new HubConnectionBuilder()
                             .WithUrl(HubLocation, transports =>
            {
                transports.HttpMessageHandlerFactory = (handler) => _webApplicationFactory.Server.CreateHandler();
            })
                             .Build();

            await connection.StartAsync();

            await connection.StopAsync();
        }
Esempio n. 17
0
        static async Task Main(string[] args)
        {
            var exitEvent = false;

            Console.CancelKeyPress += (sender, eventArgs) =>
            {
                eventArgs.Cancel = true;
                exitEvent        = true;
            };
            var clientName = ".NET Client";

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

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

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


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

                await connection.StartAsync();
            };

            await connection.StartAsync();

            while (!exitEvent)
            {
                Console.Write("> ");
                var message = Console.ReadLine();

                if (!string.IsNullOrEmpty(message))
                {
                    await connection.InvokeAsync("SendMessage", clientName, message);
                }
            }

            await connection.StopAsync();
        }
Esempio n. 18
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();
        }
        public async Task Run()
        {
            var connection = new HubConnectionBuilder()
                             .WithUrl($"{_configuration["NotificationServer:Endpoint"]}/SimulatedLongRunningTaskHub")
                             .AddMessagePackProtocol()
                             .Build();

            await connection.StartAsync();

            await connection.InvokeAsync("SendTaskStatus", "Step 1", "Begining xxx");

            Thread.Sleep(2000);

            await connection.InvokeAsync("SendTaskStatus", "Step 1", "Finished xxx");

            await connection.StopAsync();
        }
        public async Task Run()
        {
            var connection = new HubConnectionBuilder()
                             .WithUrl("http://localhost:62710/SimulatedLongRunningTaskHub")
                             .AddMessagePackProtocol()
                             .Build();

            await connection.StartAsync();

            await connection.InvokeAsync("SendTaskStatus", "Step 1", "Begining xxx");

            Thread.Sleep(2000);

            await connection.InvokeAsync("SendTaskStatus", "Step 1", "Finished xxx");

            await connection.StopAsync();
        }
Esempio n. 21
0
        public async Task <HealthCheckResult> CheckHealthAsync(HealthCheckContext context, CancellationToken cancellationToken = default)
        {
            HubConnection _connection = null;

            try
            {
                var url = GetHostAddress();
                url.Path = "/chathub";
                var authData = await GetAccessToken();

                _connection = new HubConnectionBuilder()
                              .WithUrl(url.ToString() + "?userId=" + authData.Id, options =>
                {
                    options.AccessTokenProvider = () => Task.FromResult(authData.TokenData.AccessToken);
                })
                              .WithAutomaticReconnect()
                              .Build();

                _connection.On("TestConnection", () =>
                {
                    Console.WriteLine("ChatHub is working.");
                });

                await _connection.StartAsync();

                await _connection.InvokeAsync("CheckHub");

                return(await Task.FromResult(HealthCheckResult.Healthy()));
            }
            catch (Exception e)
            {
                SentrySdk.CaptureException(e);
                return(await Task.FromResult(HealthCheckResult.Unhealthy()));
            }
            finally
            {
                if (_connection != null && _connection.State == HubConnectionState.Connected)
                {
                    await _connection.StopAsync();
                }
            }
        }
Esempio n. 22
0
        public static async Task Chat()
        {
            var connection = new HubConnectionBuilder()
                             .WithUrl("http://localhost:5005/chathub")
                             .Build();
            var msg = "";

            Console.Write("Name>");
            _userName = Console.ReadLine();

            try
            {
                await Connect(connection);
            }
            catch (HttpRequestException)
            {
                Console.WriteLine("Server not availible,press any key to exit");
                Console.ReadKey();
                msg = "exit";
            }


            while (msg != "exit")
            {
                msg = Console.ReadLine();
                switch (msg)
                {
                case "getChat":
                    await connection.InvokeAsync("GetHistory", _userName);

                    break;

                default:
                    await connection.InvokeAsync("AddMessage", msg, _userName);

                    break;
                }
            }

            await connection.StopAsync();
        }
Esempio n. 23
0
        static async Task Main(string[] args)
        {
            var connection = new HubConnectionBuilder()
                             .WithUrl("https://localhost:5001/hubs/greeter")
                             .WithAutomaticReconnect()
                             .Build();

            await connection.StartAsync();

            connection.On("ReceiveUpdate", (string stockName) =>
            {
                // show alert to the user
                Console.WriteLine($"Received update {stockName}");
            });

            await connection.InvokeAsync <string>("SubscribeOnStock", "MSFT");


            Console.ReadLine();
            await connection.StopAsync();
        }
Esempio n. 24
0
        private void ConnectSchedulerNet()
        {
            var times = Interlocked.Increment(ref _retryTimes);

            while (times <= RetryTimes)
            {
                var connection = new HubConnectionBuilder()
                                 .WithUrl($"{Service}client/?group={Group}")
                                 .Build();
                try
                {
                    OnClose(connection);
                    OnFire(connection);
                    OnWatchCallback(connection);
                    connection.StartAsync().Wait();
                    connection.SendAsync("Watch", _classNameMapTypes.Keys.ToArray()).Wait();
                }
                catch (Exception e) when(e.InnerException?.InnerException is SocketException)
                {
                    connection.StopAsync().Wait();
                    connection.DisposeAsync().Wait();
                    var exception = (SocketException)e.InnerException.InnerException;

                    if (exception.SocketErrorCode == SocketError.TimedOut || exception.SocketErrorCode == SocketError.ConnectionRefused)
                    {
                        Thread.Sleep(1000);

                        if (times <= RetryTimes)
                        {
                            Debug.WriteLine("Retry to connect scheduler.net server.");
                            continue;
                        }
                        else
                        {
                            break;
                        }
                    }
                }
            }
        }
Esempio n. 25
0
        static async Task Main(string[] args)
        {
            Console.WriteLine("Tester is awaken");

            var connection = new HubConnectionBuilder()
                             .WithUrl(new Uri("http://localhost:51818/sessionHub"))
                             .Build();

            await connection.StartAsync(CancellationToken.None);

            Console.WriteLine("Tester connected");

            var isExecuting = true;

            while (isExecuting)
            {
                var input = Console.ReadLine();

                switch (input)
                {
                case null:
                    break;

                case "q":
                    isExecuting = false;
                    break;

                case "turn":
                    await connection.InvokeAsync("RequestTurn");

                    break;
                }
            }

            await connection.StopAsync();

            await connection.DisposeAsync();

            Console.WriteLine("Tester disconnected");
        }
        public Task <HealthCheckResult> CheckHealthAsync(
            HealthCheckContext context,
            CancellationToken cancellationToken = default(CancellationToken))
        {
            try
            {
                _logger.LogDebug("Starting HubIsAliveHealthCheck");

                var connection = new HubConnectionBuilder()
                                 .WithUrl("https://localhost:4000/health")
                                 .Build();

                connection.StartAsync().Wait();
                connection.StopAsync().Wait();

                return(Task.FromResult(new HealthCheckResult(HealthStatus.Healthy)));
            }
            catch (Exception ex)
            {
                return(Task.FromResult(new HealthCheckResult(context.Registration.FailureStatus, exception: ex)));
            }
        }
        static async Task Main(string[] args)
        {
            Console.WriteLine("WebDay 2021 - SignalR : Fake Sensor Console");

            var sensorId = Guid.NewGuid();

            Console.WriteLine($"SensorId: {sensorId}");

            await using var hubConnection = new HubConnectionBuilder()
                                            .WithAutomaticReconnect()
                                            .WithUrl("https://localhost:44391/sensorhub")
                                            .Build();

            await hubConnection.StartAsync();

            await hubConnection.SendAsync("ConnectSensor", sensorId.ToString());

            Console.CancelKeyPress += new ConsoleCancelEventHandler(async(sender, args) => {
                await hubConnection.SendAsync("DisconnectSensor", sensorId.ToString());
                await hubConnection.StopAsync();

                Console.WriteLine("\nThe publish operation has been interrupted.");
            });

            Console.WriteLine("\nPress CRTL+C to exit...");

            var random = new Random();

            while (true)
            {
                var measure = random.Next(20, 22) + random.NextDouble();

                await hubConnection.SendAsync("PushSensorMeasurements", sensorId, measure);

                Console.WriteLine($"Pushed: {measure}");

                await Task.Delay(1000);
            }
        }
Esempio n. 28
0
        public async Task StopCausesPollToReturnImmediately()
        {
            using (StartVerifiableLog(out var loggerFactory))
            {
                PollTrackingMessageHandler pollTracker = null;
                var hubConnection = new HubConnectionBuilder()
                                    .WithLoggerFactory(loggerFactory)
                                    .WithUrl(ServerFixture.Url + "/default", options =>
                {
                    options.Transports = HttpTransportType.LongPolling;
                    options.HttpMessageHandlerFactory = handler =>
                    {
                        pollTracker = new PollTrackingMessageHandler(handler);
                        return(pollTracker);
                    };
                })
                                    .Build();

                await hubConnection.StartAsync();

                Assert.NotNull(pollTracker);
                Assert.NotNull(pollTracker.ActivePoll);

                var stopTask = hubConnection.StopAsync();

                try
                {
                    // if we completed running before the poll or after the poll started then the task
                    // might complete successfully
                    await pollTracker.ActivePoll.OrTimeout();
                }
                catch (OperationCanceledException)
                {
                    // If this happens it's fine because we were in the middle of a poll
                }

                await stopTask;
            }
        }
Esempio n. 29
0
        private async Task <Guid> Process(Guid idSchedulerMessaging)
        {
            AutoResetEvent waitHandler = new AutoResetEvent(false);

            using (var scope = _serviceScopeFactory.CreateScope())
            {
                var _context       = scope.ServiceProvider.GetService <DatabaseContext>();
                var _configuration = scope.ServiceProvider.GetService <IConfiguration>();

                var messaging = await _context.Scheduler_Messaging.FirstOrDefaultAsync(x => x.Id == idSchedulerMessaging);

                if (messaging == null)
                {
                    return(idSchedulerMessaging);
                }

                var idGroup = await _context.Scheduler_Messaging.Where(x => x.Id == idSchedulerMessaging).Select(x => x.Message.IdGroup).FirstOrDefaultAsync();

                //var connection = new HubConnectionBuilder().WithUrl("http://localhost:9854/messaginghub").Build();
                var connection = new HubConnectionBuilder().WithUrl(_configuration.GetValue <string>("SiteUrl") + "/messaginghub").Build();
                await connection.StartAsync();

                connection.On("ProgressFinished", new Type[] { typeof(Guid) }, (idMessaging) => Task.Run(() => waitHandler.Set()));

                await connection.InvokeAsync("Subscribe", idGroup);

                await connection.InvokeAsync("Start", idGroup, idSchedulerMessaging);

                waitHandler.WaitOne();

                await connection.StopAsync();

                messaging.Status = Models.Database.Common.MessagingStatus.Finished;
                messaging.DtEnd  = DateTime.UtcNow;
                await _context.SaveChangesAsync();

                return(idSchedulerMessaging);
            }
        }
Esempio n. 30
0
        static async Task Main(string[] args)
        {
            var connection = new HubConnectionBuilder()
                             .WithUrl("https://localhost:5001/Chat")
                             .Build();

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

                // await connection.StartAsync();
            };

            await connection.StartAsync();

            connection.On <DataEventArgs>("ReceiveMessage", (e) =>
            {
                Console.WriteLine(e.Pressure1);
            });

            while (true)
            {
                var key = Console.ReadKey();
                if (key.Key == ConsoleKey.S)
                {
                    await connection.SendAsync("SendMessage", "send method", "hello from send");
                }
                else if (key.Key == ConsoleKey.I)
                {
                    await connection.InvokeAsync("SendMessage", "invoke method", "hello from invoke");
                }
                else
                {
                    await connection.StopAsync();
                }
            }
        }