async static Task Main(string[] args)
        {
            var configuration = new ConfigurationBuilder()
                                .SetBasePath(Directory.GetCurrentDirectory())
                                .AddUserSecrets <Program>()
                                .Build();

            serviceUtils = new ServiceUtils(configuration["Azure:SignalR:ConnectionString"]);

            var url = $"{serviceUtils.Endpoint}:5001/client/?hub={hubName}";

            hubConnection = new HubConnectionBuilder()
                            .WithUrl(url, option =>
            {
                option.AccessTokenProvider = () =>
                {
                    return(Task.FromResult(serviceUtils.GenerateAccessToken(url, userId)));
                };
            }).Build();

            hubConnection.On <string, string>("SendMessage",
                                              (string server, string message) =>
            {
                Console.WriteLine($"Message from server {server}: {message}");
            });

            await hubConnection.StartAsync();

            Console.WriteLine("Client started... Press any key to close the connection");
            Console.ReadLine();
            await hubConnection.DisposeAsync();

            Console.WriteLine("Client is shutting down...");
        }
Exemple #2
0
        protected async Task StartSendingMessageAsync(int index, string targetUserId,
                                                      byte[] messageBlob, int duration, int interval, Counter counter)
        {
            var messageSize = (ulong)messageBlob.Length;
            await Task.Delay(StartTimeOffsetGenerator.Delay(TimeSpan.FromSeconds(interval)));

            using (var cts = new CancellationTokenSource(TimeSpan.FromSeconds(duration)))
            {
                while (!cts.IsCancellationRequested)
                {
                    _ = Task.Run(async() =>
                    {
                        try
                        {
                            var url     = GenRestUrl(_serviceUtils, targetUserId);
                            var request = new HttpRequestMessage(HttpMethod.Post, GetUrl(url));
                            // Corefx changed the default version and High Sierra curlhandler tries to upgrade request
                            request.Version = new Version(1, 1);
                            request.Headers.Authorization =
                                new AuthenticationHeaderValue("Bearer",
                                                              _serviceUtils.GenerateAccessToken(url, _serverName));
                            request.Headers.Accept.Add(new MediaTypeWithQualityHeaderValue("application/json"));
                            var payloadRequest = new PayloadMessage
                            {
                                Target    = ServiceUtils.MethodName,
                                Arguments = new[]
                                {
                                    _serverName,
                                    $"{DateTimeOffset.UtcNow.ToUnixTimeMilliseconds()}",
                                    _content
                                }
                            };
                            request.Content = new StringContent(JsonConvert.SerializeObject(payloadRequest), Encoding.UTF8, "application/json");
                            // ResponseHeadersRead instructs SendAsync to return once headers are read
                            // rather than buffer the entire response. This gives a small perf boost.
                            // Note that it is important to dispose of the response when doing this to
                            // avoid leaving the connection open.
                            using (var response = await _tk.HttpClients[index].SendAsync(request, HttpCompletionOption.ResponseHeadersRead))
                            {
                                response.EnsureSuccessStatusCode();
                            }
                            counter.IncreaseSentMessageSize(messageSize);
                            counter.IncreseSentMsg();
                        }
                        catch (Exception ex)
                        {
                            Util.Log($"exception in sending message of {index}th connection: {ex}");
                            //counter.IncreaseConnectionError();
                            counter.IncreseNotSentFromClientMsg();
                        }
                    });

                    // sleep for the fixed interval
                    await Task.Delay(TimeSpan.FromSeconds(interval));
                }
            }
        }
        public ClientHandler(string connectionString, string hubName, string userId)
        {
            var serviceUtils = new ServiceUtils(connectionString);

            var url = GetClientUrl(serviceUtils.Endpoint, hubName);

            _connection = new HubConnectionBuilder()
                          .WithUrl(url, option =>
            {
                option.AccessTokenProvider = () =>
                {
                    return(Task.FromResult(serviceUtils.GenerateAccessToken(url, userId)));
                };
            }).Build();

            _connection.On <string, string>("SendMessage",
                                            (string server, string message) =>
            {
                Console.WriteLine($"[{DateTime.Now.ToString()}] Received message from server {server}: {message}");
            });
        }
Exemple #4
0
        private static async void Broadcast(string message)
        {
            var url     = $"{serviceUtils.Endpoint}:5002/api/v1-preview/hub/{hubName.ToLower()}";
            var request = new HttpRequestMessage(HttpMethod.Post, new UriBuilder(url).Uri);

            request.Headers.Authorization =
                new AuthenticationHeaderValue("Bearer", serviceUtils.GenerateAccessToken(url, serverName));
            request.Headers.Accept.Add(new MediaTypeWithQualityHeaderValue("application/json"));
            var messageContent = new MessageContent()
            {
                Target = "SendMessage", Arguments = new[] { serverName, message }
            };

            request.Content = new StringContent(JsonConvert.SerializeObject(messageContent), Encoding.UTF8, "application/json");

            var response = await httpClient.SendAsync(request);

            if (response.StatusCode != HttpStatusCode.Accepted)
            {
                Console.WriteLine($"Sent error: {response.StatusCode}");
            }
        }
Exemple #5
0
        private List <HubConnection> Create(int startCliIndex, int endCliIndex, string url,
                                            string transportTypeName = "Websockets",
                                            string hubProtocol       = "json")
        {
            Util.Log($"transport type: {transportTypeName}");
            var transportType = HttpTransportType.WebSockets;

            switch (transportTypeName)
            {
            case "LongPolling":
                transportType = HttpTransportType.LongPolling;
                break;

            case "ServerSentEvents":
                transportType = HttpTransportType.ServerSentEvents;
                break;

            case "None":
                transportType = HttpTransportType.None;
                break;

            default:
                transportType = HttpTransportType.WebSockets;
                break;
            }
            Util.Log($"Connection string: {url}");
            var serviceUtils = new ServiceUtils(url);

            _tk.State = Stat.Types.State.HubconnCreating;
            var connections = new List <HubConnection>(endCliIndex - startCliIndex);

            for (var i = startCliIndex; i < endCliIndex; i++)
            {
                var serviceUrl = serviceUtils.GetClientUrl();
                var userId     = $"{ServiceUtils.ClientUserIdPrefix}{i}";

                var cookies           = new CookieContainer();
                var httpClientHandler = new HttpClientHandler
                {
                    ServerCertificateCustomValidationCallback = HttpClientHandler.DangerousAcceptAnyServerCertificateValidator,
                    CookieContainer = cookies,
                };
                var hubConnectionBuilder = new HubConnectionBuilder()

                                           /* TODO. Console log is important for finding errors.
                                            * But if every connection enables it, there will be thousands of
                                            * 'Console logger queue processing thread' which degrade the system
                                            * response, and bring issues to counters statistic.
                                            * Temporarily, we disable it. We need to find the best way
                                            * to enable it.
                                            */
                                           //.ConfigureLogging(logging =>
                                           //{
                                           //    logging.AddConsole();
                                           //    logging.SetMinimumLevel(LogLevel.Warning);
                                           //})
                                           .WithUrl(serviceUrl, httpConnectionOptions =>
                {
                    httpConnectionOptions.HttpMessageHandlerFactory = _ => httpClientHandler;
                    httpConnectionOptions.Transports          = transportType;
                    httpConnectionOptions.CloseTimeout        = TimeSpan.FromMinutes(100);
                    httpConnectionOptions.Cookies             = cookies;
                    httpConnectionOptions.AccessTokenProvider = () =>
                    {
                        return(Task.FromResult(serviceUtils.GenerateAccessToken(serviceUrl, userId)));
                    };
                });

                HubConnection connection = null;
                switch (hubProtocol)
                {
                case "json":
                    connection = hubConnectionBuilder.Build();
                    break;

                case "messagepack":
                    connection = hubConnectionBuilder.AddMessagePackProtocol().Build();
                    break;

                default:
                    throw new Exception($"{hubProtocol} is invalid.");
                }

                connection.Closed += e =>
                {
                    if (_tk.State <= Stat.Types.State.SendComplete && _tk.State >= Stat.Types.State.SendReady)
                    {
                        var error = $"Connection closed early: {e}";
                        Util.Log(error);
                    }

                    return(Task.CompletedTask);
                };
                connections.Add(connection);
            }

            _tk.State = Stat.Types.State.HubconnCreated;
            return(connections);
        }