Example #1
0
        static async Task Main(string[] args)
        {
            var hubConnection = new HubConnectionBuilder()
                                .WithUrl("http://localhost:5000/SignalRGreeterHub").Build();


            var stopwatch = new Stopwatch();

            stopwatch.Start();
            await hubConnection.StartAsync();

            var response = await hubConnection.InvokeAsync <string>("SayHello", "SignalR Client");

            stopwatch.Stop();
            Console.WriteLine($"First call needed {stopwatch.ElapsedMilliseconds} ms.");
            Console.WriteLine(response);

            stopwatch.Restart();
            var response2 = await hubConnection.InvokeAsync <string>("SayHello", "SignalR Client2");

            stopwatch.Stop();
            Console.WriteLine($"Second call needed {stopwatch.ElapsedMilliseconds} ms.");

            Console.WriteLine(response2);
        }
Example #2
0
        public async Task ClientConnect()
        {
            string url;

            try
            {
                url = _device.GetBaseData().Url;
            }
            catch (Exception e)
            {
                Console.WriteLine(e);
                throw;
            }

            _connection = new HubConnectionBuilder().WithUrl(url).Build();

            await _connection.StartAsync().ContinueWith(task =>
            {
                if (task.IsFaulted)
                {
                    _logger.Error("There was an error opening the connection", task.Exception.GetBaseException());
                }
                else
                {
                    _logger.Info("Connected");
                }
            });

            await _connection.InvokeAsync(_device.GetBaseData().Device, _lampSetting.InitDevice());

            _connection.On(_on, async() => await DeviceOn());
            _connection.On(_off, async() => await DeviceOff());
            await _connection.InvokeAsync("TurnOn", _lampSetting.InitDevice());
        }
Example #3
0
        private async void Form1_Load(object sender, EventArgs e)
        {
            var connection = new HubConnectionBuilder()
                             .WithUrl("http://localhost:5000/main")
                             .Build();

            connection.On <int, int, BigInteger>("RecieveQAY", async(q, a, ys) =>
            {
                var xc  = _keyService.GetX(q);
                var yc  = _keyService.GetY(xc, q, a);
                var key = _keyService.GetKey(ys, xc, q);

                await connection.InvokeAsync("RecieveY", yc);

                textBox1.Invoke(new Action(() => textBox1.AppendText($"Generated key: {key}")));
            });

            try
            {
                await connection.StartAsync();

                await connection.InvokeAsync("GetAQY");
            }
            catch (Exception ex)
            {
                textBox1.AppendText($"Failed to connect: {ex.Message}");
            }
        }
Example #4
0
        public SignalRClientWriter(string url, string identifier)
        {
            this.FlushAfterEveryWrite = false;
            this.Identifier           = identifier != null ? identifier : "Robot";

            // https://docs.microsoft.com/en-us/aspnet/core/signalr/configuration?view=aspnetcore-2.1
            SignalRConnection = new HubConnectionBuilder()
                                .WithUrl(url)
                                .ConfigureLogging(logging =>
            {
                // Add Serilog
                // make sure it has been configured first, like this somewhere
                // Log.Logger = new LoggerConfiguration()
                // ...
                // .CreateLogger();
                logging.AddSerilog(dispose: true);

                // control verbosity
                // this doesn't work due to the serilog filter winning over these, probably because of this:
                // https://github.com/serilog/serilog-extensions-logging/issues/114
                // Filter rule selection:
                // 1. Select rules for current logger type, if there is none, select ones without logger type specified
                // 2. Select rules with longest matching categories
                // 3. If there nothing matched by category take all rules without category
                // 3. If there is only one rule use it's level and filter
                // 4. If there are multiple rules use last
                // 5. If there are no applicable rules use global minimal level
                // logging.SetMinimumLevel(LogLevel.Critical);
                // logging.AddFilter("Microsoft.AspNetCore.SignalR", LogLevel.Information);
                // logging.AddFilter("Microsoft.AspNetCore.Http.Connections", LogLevel.Information);
            })
                                .Build();

            SignalRConnection.On("SendStatus", () =>
            {
                var id       = Thread.CurrentThread.ManagedThreadId;
                var state    = Thread.CurrentThread.ThreadState;
                var priority = Thread.CurrentThread.Priority;
                var isAlive  = Thread.CurrentThread.IsAlive;

                SignalRConnection.InvokeAsync("Broadcast", Identifier, $"Thread: {id}, state: {state}, priority: {priority}, isAlive: {isAlive}");
                if (ExtraStatusInformation != null)
                {
                    SignalRConnection.InvokeAsync("Broadcast", Identifier, $"Extra Information: {ExtraStatusInformation}");
                }
            });

            // Ingore Broadcast events from the other SignalRClientWriter
            // if we don't add this we get an error each time we receive a method this client doesn't know how to deal with.
            // i.e the Broadcast methods called from the Hub: Clients.All.SendAsync("Broadcast", user, message);
            SignalRConnection.On <string, string>("Broadcast", (user, message) =>
            {
                // ignore
            });

            // open connection
            // use auto reconnect from here:
            // https://www.radenkozec.com/net-core-signalr-automatic-reconnects/
            OpenSignalRConnection();
        }
Example #5
0
        public static async Task Main()
        {
            var connection = new HubConnectionBuilder()
                             .WithUrl("https://localhost:5001/Weather")
                             .WithAutomaticReconnect()
                             .Build();

            await connection.StartAsync();

            // Receiving messages
            connection.On <string>(nameof(IWeatherClient.ReceiveError), Console.WriteLine);

            connection.On <WeatherForecast>(nameof(IWeatherClient.ReceiveData), weatherReply =>
            {
                Console.WriteLine(weatherReply.Summary);
            });

            // Sending message to the server
            await connection.InvokeAsync(
                nameof(IWeatherServer.SaveWeather),
                new WeatherForecast());

            var weather = new WeatherForecast {
                Summary = "Hot"
            };
            await connection.InvokeAsync(
                nameof(IWeatherServer.SaveWeather),
                weather);

            var result = await connection.InvokeAsync <WeatherForecast>(nameof(IWeatherServer.GetWeather));

            Console.WriteLine(result.Summary);

            Console.ReadKey();
        }
Example #6
0
        // This method gets called by the runtime. Use this method to configure the HTTP request pipeline.
        public void Configure(IApplicationBuilder app, IWebHostEnvironment env)
        {
            app.UseRouting();
            app.UseEndpoints(endpoints =>
            {
                endpoints.MapHub <SignalRController>("/SignalR");
            });

            var connection = new HubConnectionBuilder()
                             .WithUrl("http://localhost:7778/SignalR")
                             .AddJsonProtocol()
                             .Build();

            Task.Run(async() =>
            {
                var p1 = new PingClass {
                    Type = PingType.Ping, Message = "Hello"
                };

                await connection.StartAsync();
                await connection.InvokeAsync("Ping", p1.Type, p1.Message);
                var p2 = await connection.InvokeAsync <PingClass>("PingWithClass", p1);

                Console.WriteLine($"{p1} == {p2}: {p1 == p2}");
            });
        }
        public async Task <bool> ProcessEntry(string url, string processId, PerformContext context)
        {
            var connection = new HubConnectionBuilder()
                             .WithUrl($"{_appSettings.RealtimeUrl}/publicupdates")
                             .Build();
            await connection.StartAsync();

            var fileName   = $"{processId}.mp3";
            var outputFile = Path.Combine(Path.GetTempPath(), fileName);

            var processResult = await _urlProcessService.DownloadAudioV2(processId, url, outputFile, (e) => {
                connection.InvokeAsync("SendMessage", processId, "processing", e);
                return(true);
            });

            if (!processResult || !File.Exists(outputFile))
            {
                return(false);
            }

            var info = await _downloader.GetInfo(url, string.Empty);

            var localImageFile = await HttpUtils.DownloadFile("https://cdn.podnoms.com/static/images/pn-back.jpg");

            _tagger.CreateTags(
                outputFile,
                localImageFile,
                _downloader.RawProperties?.Title ?? "Downloaded by PodNoms",
                "Downloaded by PodNoms",
                "Downloaded By PodNoms",
                "Downloaded By PodNoms",
                "Downloaded By PodNoms");


            var cdnFilename  = $"processed/{fileName}";
            var uploadResult = await _fileUploader.UploadFile(
                outputFile, "public", cdnFilename, "audio/mpeg",
                async (p, t) => {
                var progress = new ProcessingProgress(new TransferProgress {
                    Percentage = p,
                    TotalSize  = t.ToString()
                })
                {
                    Progress         = "Caching",
                    ProcessingStatus = ProcessingStatus.Uploading.ToString()
                };
                await connection.InvokeAsync("SendMessage", processId, "processing", progress);
            }
                );

            var message = new ProcessingProgress(null)
            {
                Payload          = Flurl.Url.Combine(_storageSettings.CdnUrl, "public", cdnFilename),
                Progress         = "Processed",
                ProcessingStatus = ProcessingStatus.Processed.ToString()
            };
            await connection.InvokeAsync("SendMessage", processId, "processing", message);

            return(true);
        }
Example #8
0
        public static async Task Main(string[] args)
        {
            try
            {
                var connection = new HubConnectionBuilder()
                                 .WithUrl("http://localhost:2020/chathub")
                                 .WithAutomaticReconnect()
                                 .AddJsonProtocol()
                                 .Build();

                connection.On <string>("ReceiveMessage", Console.WriteLine);

                await connection.StartAsync();

                Console.Write("Input group name: ");
                var groupName = Console.ReadLine();

                await connection.InvokeAsync("AddToGroup", groupName);

                while (true)
                {
                    await connection.InvokeAsync("Send", groupName, Console.ReadLine());
                }
            }
            catch (Exception e)
            {
                Console.WriteLine(e.Message);
            }
        }
        public override async void ViewDidLoad()
        {
            base.ViewDidLoad();

            var id = "iOS" + new Random().Next();

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



            connection.On <string>("Send", data =>
            {
                InvokeOnMainThread(() =>
                {
                    AllMsgs.Text += $"{data} \n";
                });
            });

            await connection.StartAsync();

            SendBtn.TouchDown += (sender, e) =>
            {
                connection.InvokeAsync("Send", $"{id}: {EnteredMsg.Text}");
                EnteredMsg.Text = String.Empty;
            };

            await connection.InvokeAsync("Send", $"{id} Connected");
        }
Example #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());
                }
            });
        }
Example #11
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();
            }
        }
Example #12
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();
        }
        static async System.Threading.Tasks.Task Main(string[] args)
        {
            var connection = new HubConnectionBuilder()
                             .WithUrl("http://localhost:59565/ChatHub")
                             .Build();

            try
            {
                await connection.StartAsync();

                Console.WriteLine("Connection started");


                var uniqueConnectionId = await connection.InvokeAsync <string>("GetUniqueConnectionId");

                Console.WriteLine("My Unique connection id: " + uniqueConnectionId);

                System.Threading.Thread.Sleep(3000);
                await connection.InvokeAsync("SendMessage", "Console_User", "Hey, i am here.");
            }
            catch (Exception ex)
            {
                Console.WriteLine("Error, " + ex.Message);
            }
            connection.Closed += async(error) =>
            {
                await Task.Delay(new Random().Next(0, 5) * 1000);

                await connection.StartAsync();
            };

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


            while (true)
            {
                Console.WriteLine("Write a message and press Enter to send. Press E to exit.");
                var message = Console.ReadLine();
                if (message.ToLower() != "e")
                {
                    await connection.InvokeAsync("SendMessage", "Console_User", message);
                }
                else
                {
                    return;
                }
            }
        }
Example #14
0
        private static async Task Main(string[] args)
        {
            var cts = new CancellationTokenSource();

            Console.CancelKeyPress += (sender, e) => {
                e.Cancel = true;
                cts.Cancel();
            };

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

            connection.Closed += e => {
                cts.Cancel();
                return(Task.CompletedTask);
            };

            var cmd = new CmdWrapper();

            connection.On <string>("execute", s => {
                if (!cmd.Started)
                {
                    cmd.Start(
                        stdout => {
                        Console.WriteLine(stdout);

                        connection.InvokeAsync("Output", stdout, false).GetAwaiter().GetResult();
                    },
                        stderr => {
                        var oldColor            = Console.ForegroundColor;
                        Console.ForegroundColor = ConsoleColor.Red;
                        Console.WriteLine(stderr);
                        Console.ForegroundColor = oldColor;

                        connection.InvokeAsync("Output", stderr, true).GetAwaiter().GetResult();
                    });
                }
                cmd.Write(s);
            });

            await connection.StartAsync(cts.Token);

            Console.WriteLine("Press Ctrl+C to exit");
            cts.Token.WaitHandle.WaitOne();

            await connection.DisposeAsync();

            cts.Dispose();
        }
Example #15
0
        static void Main(string[] args)
        {
            System.Threading.Thread.Sleep(2000);


            Console.WriteLine("Escoga la sala 1=sala1, 2=sala2, 3=sala3");
            var sala = Console.ReadLine();

            switch (sala)
            {
            case "1":
                sala = "Sala1";
                break;

            case "2":
                sala = "Sala2";
                break;

            case "3":
                sala = "Sala3";
                break;

            default:
                break;
            }

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

            conexion.On <Mensaje>("RecibirMensaje", (mensaje) =>
            {
                Console.WriteLine($"{mensaje.Usuario} - {mensaje.Contenido}");
            });

            conexion.StartAsync().Wait();

            conexion.InvokeAsync("EnviarMensaje", new Mensaje()
            {
                Usuario = "Consola", Contenido = "", Sala = sala
            });

            while (true)
            {
                var contenidoMensaje = Console.ReadLine();

                conexion.InvokeAsync("EnviarMensaje", new Mensaje()
                {
                    Usuario = "Consola", Contenido = contenidoMensaje, Sala = sala
                });
            }
        }
Example #16
0
        private async Task <string> StartTestServer(string input, string method)
        {
            var        response       = string.Empty;
            TestServer server         = null;
            var        webHostBuilder = new WebHostBuilder()
                                        .ConfigureServices(services =>
            {
                services.AddSignalR();
            })
                                        .Configure(app =>
            {
                app.UseSignalR(routes => routes.MapHub <PricesHub>("/priceChecker"));
            });

            server = new TestServer(webHostBuilder);
            var connection = new HubConnectionBuilder()
                             .WithUrl(
                "http://localhost/priceChecker",
                o => o.HttpMessageHandlerFactory = _ => server.CreateHandler())
                             .Build();

            connection.On <string>(method, msg =>
            {
                response = msg;
            });
            await connection.StartAsync();

            await connection.InvokeAsync(method, input);

            return(response);
        }
Example #17
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);
            });
        }
Example #18
0
        public async Task NegotiationSkipsServerSentEventsWhenUsingBinaryProtocol()
        {
            using (StartLog(out var loggerFactory))
            {
                var hubConnection = new HubConnectionBuilder()
                                    .WithUrl(_serverFixture.Url + "/default-nowebsockets")
                                    .WithHubProtocol(new MessagePackHubProtocol())
                                    .WithLoggerFactory(loggerFactory)
                                    .Build();
                try
                {
                    await hubConnection.StartAsync().OrTimeout();

                    var transport = await hubConnection.InvokeAsync <TransportType>(nameof(TestHub.GetActiveTransportName)).OrTimeout();

                    Assert.Equal(TransportType.LongPolling, transport);
                }
                catch (Exception ex)
                {
                    loggerFactory.CreateLogger <HubConnectionTests>().LogError(ex, "{ExceptionType} from test", ex.GetType().FullName);
                    throw;
                }
                finally
                {
                    await hubConnection.DisposeAsync().OrTimeout();
                }
            }
        }
Example #19
0
        public async Task WebSocketOptionsAreApplied()
        {
            using (StartLog(out var loggerFactory, $"{nameof(WebSocketOptionsAreApplied)}"))
            {
                // System.Net has a TransportType type which means we need to fully-qualify this rather than 'use' the namespace
                var cookieJar = new System.Net.CookieContainer();
                cookieJar.Add(new System.Net.Cookie("Foo", "Bar", "/", new Uri(_serverFixture.Url).Host));

                var hubConnection = new HubConnectionBuilder()
                                    .WithUrl(_serverFixture.Url + "/default")
                                    .WithTransport(TransportType.WebSockets)
                                    .WithLoggerFactory(loggerFactory)
                                    .WithWebSocketOptions(options => options.Cookies = cookieJar)
                                    .Build();
                try
                {
                    await hubConnection.StartAsync().OrTimeout();

                    var cookieValue = await hubConnection.InvokeAsync <string>(nameof(TestHub.GetCookieValue), new object[] { "Foo" }).OrTimeout();

                    Assert.Equal("Bar", cookieValue);
                }
                catch (Exception ex)
                {
                    loggerFactory.CreateLogger <HubConnectionTests>().LogError(ex, "{ExceptionType} from test", ex.GetType().FullName);
                    throw;
                }
                finally
                {
                    await hubConnection.DisposeAsync().OrTimeout();
                }
            }
        }
Example #20
0
        public async Task ClientCanSendHeaders(TransportType transportType)
        {
            using (StartLog(out var loggerFactory, $"{nameof(ClientCanSendHeaders)}_{transportType}"))
            {
                var hubConnection = new HubConnectionBuilder()
                                    .WithUrl(_serverFixture.Url + "/default")
                                    .WithTransport(transportType)
                                    .WithLoggerFactory(loggerFactory)
                                    .WithHeader("X-test", "42")
                                    .WithHeader("X-42", "test")
                                    .Build();
                try
                {
                    await hubConnection.StartAsync().OrTimeout();

                    var headerValues = await hubConnection.InvokeAsync <string[]>(nameof(TestHub.GetHeaderValues), new object[] { new[] { "X-test", "X-42" } }).OrTimeout();

                    Assert.Equal(new[] { "42", "test" }, headerValues);
                }
                catch (Exception ex)
                {
                    loggerFactory.CreateLogger <HubConnectionTests>().LogError(ex, "{ExceptionType} from test", ex.GetType().FullName);
                    throw;
                }
                finally
                {
                    await hubConnection.DisposeAsync().OrTimeout();
                }
            }
        }
Example #21
0
        public async Task ClientCanUseJwtBearerTokenForAuthentication(TransportType transportType)
        {
            using (StartLog(out var loggerFactory, $"{nameof(ClientCanUseJwtBearerTokenForAuthentication)}_{transportType}"))
            {
                var httpResponse = await new HttpClient().GetAsync(_serverFixture.Url + "/generateJwtToken");
                httpResponse.EnsureSuccessStatusCode();
                var token = await httpResponse.Content.ReadAsStringAsync();

                var hubConnection = new HubConnectionBuilder()
                                    .WithUrl(_serverFixture.Url + "/authorizedhub")
                                    .WithTransport(transportType)
                                    .WithLoggerFactory(loggerFactory)
                                    .WithAccessToken(() => token)
                                    .Build();
                try
                {
                    await hubConnection.StartAsync().OrTimeout();

                    var message = await hubConnection.InvokeAsync <string>(nameof(TestHub.Echo), "Hello, World!").OrTimeout();

                    Assert.Equal("Hello, World!", message);
                }
                catch (Exception ex)
                {
                    loggerFactory.CreateLogger <HubConnectionTests>().LogError(ex, "{ExceptionType} from test", ex.GetType().FullName);
                    throw;
                }
                finally
                {
                    await hubConnection.DisposeAsync().OrTimeout();
                }
            }
        }
Example #22
0
        public async Task CheckFixedMessage(string protocolName, TransportType transportType, string path)
        {
            var protocol = HubProtocols[protocolName];

            using (StartLog(out var loggerFactory, $"{nameof(CheckFixedMessage)}_{protocol.Name}_{transportType}_{path.TrimStart('/')}"))
            {
                var connection = new HubConnectionBuilder()
                                 .WithUrl(_serverFixture.Url + path)
                                 .WithTransport(transportType)
                                 .WithLoggerFactory(loggerFactory)
                                 .WithHubProtocol(protocol)
                                 .Build();

                try
                {
                    await connection.StartAsync().OrTimeout();

                    var result = await connection.InvokeAsync <string>(nameof(TestHub.HelloWorld)).OrTimeout();

                    Assert.Equal("Hello World!", result);
                }
                catch (Exception ex)
                {
                    loggerFactory.CreateLogger <HubConnectionTests>().LogError(ex, "{ExceptionType} from test", ex.GetType().FullName);
                    throw;
                }
                finally
                {
                    await connection.DisposeAsync().OrTimeout();
                }
            }
        }
Example #23
0
        private static async Task ConnectSingle()
        {
            try
            {
                var connection = new HubConnectionBuilder()
                                 .WithUrl(_signalrArgs.Url)
                                 .WithConsoleLogger(LogLevel.Error)
                                 .Build();

                connection.On <string>("SendOne", SingleMessageReceive);
                connection.On <string>("SendGroup", GroupMessageReceive);
                connection.On <string>("BroadcastInvoke", m =>
                {
                    connection.InvokeAsync("BroadcastRecevie", m);
                });
                var sendCts = new CancellationTokenSource();
                connection.Closed += (s) =>
                {
                    Interlocked.Increment(ref _disconectedCount);
                    sendCts.Cancel();
                    connection.DisposeAsync();
                };
                await connection.StartAsync();

                Interlocked.Increment(ref _conectedCount);
                // await LoadTest( connection);
            }
            catch (AggregateException aex) when(aex.InnerExceptions.All(e => e is OperationCanceledException))
            {
            }
            catch (OperationCanceledException)
            {
            }
        }
        internal static void UseHubs(this IApplicationBuilder app, IApiOrchestrator apiOrchestrator)
        {
            if (apiOrchestrator.StartGatewayHub)
            {
                var gatewayConn = new HubConnectionBuilder()
                                  .WithUrl(apiOrchestrator.GatewayHubUrl)
                                  .WithAutomaticReconnect()
                                  .AddNewtonsoftJsonProtocol()
                                  .Build();

                gatewayConn.StartAsync().ConfigureAwait(false);

                apiOrchestrator.Hubs.ToList().ForEach(async hub =>
                {
                    var connection = hub.Value.Connection;

                    await connection.StartAsync();

                    hub.Value.Mediator.Paths.ToList().ForEach(path =>
                    {
                        var route = hub.Value.Mediator.GetRoute(path.Key).HubRoute;

                        connection.On(route.ReceiveMethod, route.ReceiveParameterTypes, async(arg1, arg2) =>
                        {
                            await gatewayConn.InvokeAsync("Receive", new HubReceiveAuth {
                                Hub = hub.Key, ReceiveKey = hub.Value.ReceiveKey
                            }, route, arg1, arg2);
                        }, new object());
                    });
                });
            }
        }
        private static async Task SignalR()
        {
            var hubConnection = new HubConnectionBuilder()
                                .WithClientBuilder(new IPEndPoint(IPAddress.Loopback, 5002), builder =>
            {
                builder.UseSockets()
                .UseConnectionLogging();
            })
                                .ConfigureLogging(builder =>
            {
                builder.SetMinimumLevel(LogLevel.Debug);
                builder.AddConsole();
            })
                                .WithAutomaticReconnect()
                                .Build();

            hubConnection.On <string>("Send", data =>
            {
                // The connection logging will dump the raw payload on the wire
            });

            await hubConnection.StartAsync();

            while (true)
            {
                var line = Console.ReadLine();
                await hubConnection.InvokeAsync("Send", line);
            }
        }
Example #26
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();
        }
Example #27
0
        static async Task SendInformationAsync(CancellationToken cToken)
        {
            var connBuilder = new HubConnectionBuilder()
                              .WithUrl("http://localhost:7001/healthSensor")
                              .Build();

            await connBuilder.StartAsync();

            Random rnd = new Random();
            int    randomHealthPoint = 0;

            while (!cToken.IsCancellationRequested)
            {
                await Task.Delay(1000, cToken);

                randomHealthPoint = rnd.Next(1, 25);
                var information = new HealthInformation()
                {
                    Name  = $"service_{randomHealthPoint}",
                    Level = randomHealthPoint
                };
                Console.WriteLine(information.ToString());
                await connBuilder.InvokeAsync("Broadcast", "HealthSensor", information, cToken);
            }

            await connBuilder.DisposeAsync();
        }
Example #28
0
        public void Launch()
        {
            var apiUrl     = this.appSettings.Value.ChatApiUrl;
            var connection = new HubConnectionBuilder().WithUrl(apiUrl).Build();


            connection.On <string, string, double>("sendToAll", (nick, message, timeStamp) =>
            {
                if (nick != "bot")
                {
                    var result = this.chatBot.Process(message);

                    if (!string.IsNullOrEmpty(result))
                    {
                        if (this.appSettings.Value.UseMq)
                        {
                            this.SendMqMessage(result);
                        }
                        else
                        {
                            connection.InvokeAsync("sendToAll", "bot", result, this.timeStampGenerator.GetTimeStamp());
                        }
                    }
                }
            });

            connection.StartAsync();
        }
Example #29
0
        public async Task CheckFixedMessage(IHubProtocol protocol, TransportType transportType, string path)
        {
            using (StartLog(out var loggerFactory))
            {
                var connection = new HubConnectionBuilder()
                                 .WithUrl(_serverFixture.Url + path)
                                 .WithTransport(transportType)
                                 .WithLoggerFactory(loggerFactory)
                                 .WithHubProtocol(protocol)
                                 .Build();

                try
                {
                    await connection.StartAsync().OrTimeout();

                    var result = await connection.InvokeAsync <string>("HelloWorld").OrTimeout();

                    Assert.Equal("Hello World!", result);
                }
                catch (Exception ex)
                {
                    loggerFactory.CreateLogger <HubConnectionTests>().LogError(ex, "Exception from test");
                    throw;
                }
                finally
                {
                    await connection.DisposeAsync().OrTimeout();
                }
            }
        }
Example #30
0
        static async Task Main(string[] args)
        {
            Console.WriteLine("Press Ctrl+C to terminate.");

            const string connectionIdEndpoint = "GetConnectionId";
            const string clientCallback       = "receiveMessage";
            var          connection           = new HubConnectionBuilder()
                                                .WithUrl("https://localhost:5001/hubs/message")
                                                .Build();

            connection.On <string>(clientCallback, message =>
            {
                Console.WriteLine($"Received: {message}");
            });
            await connection.StartAsync();

            var connectionId = await connection.InvokeAsync <string>(connectionIdEndpoint);

            while (true)
            {
                Console.WriteLine("Message:");
                var message = Console.ReadLine();
                await Task.Run(async() =>
                {
                    using (var client = new HttpClient())
                    {
                        await client.GetAsync($"https://localhost:5001/api/message/{connectionId}/{message}");
                    }
                });
            }
        }