Exemple #1
0
        public async Task VerifyUserOptionsAreNotChanged()
        {
            using (StartVerifiableLog())
            {
                HttpConnectionOptions originalOptions = null, resolvedOptions = null;
                var accessTokenFactory = new Func <Task <string> >(() => Task.FromResult("fakeAccessToken"));
                var fakeHeader = "fakeHeader";

                var connection = new HubConnectionBuilder()
                                 .WithUrl("http://example.com", Http.Connections.HttpTransportType.WebSockets,
                                          options =>
                {
                    originalOptions         = options;
                    options.SkipNegotiation = true;
                    options.Headers.Add(fakeHeader, "value");
                    options.AccessTokenProvider = accessTokenFactory;
                    options.WebSocketFactory    = (context, token) =>
                    {
                        resolvedOptions = context.Options;
                        return(ValueTask.FromResult <WebSocket>(null));
                    };
                })
                                 .Build();

                try
                {
                    // since we returned null WebSocket it would fail
                    await Assert.ThrowsAsync <InvalidOperationException>(() => connection.StartAsync().DefaultTimeout());
                }
                finally
                {
                    await connection.DisposeAsync().DefaultTimeout();
                }

                Assert.NotNull(resolvedOptions);
                Assert.NotNull(originalOptions);
                // verify that object was copied
                Assert.NotSame(resolvedOptions, originalOptions);
                Assert.NotSame(resolvedOptions.AccessTokenProvider, originalOptions.AccessTokenProvider);
                // verify original object still points to the same provider
                Assert.Same(originalOptions.AccessTokenProvider, accessTokenFactory);
                Assert.Same(resolvedOptions.Headers, originalOptions.Headers);
                Assert.Contains(fakeHeader, resolvedOptions.Headers);
            }
        }
        private HubConnection buildConnection(CancellationToken cancellationToken)
        {
            var builder = new HubConnectionBuilder()
                          .WithUrl(endpoint, options =>
            {
                // Use HttpClient.DefaultProxy once on net6 everywhere.
                // The credential setter can also be removed at this point.
                options.Proxy = WebRequest.DefaultWebProxy;
                if (options.Proxy != null)
                {
                    options.Proxy.Credentials = CredentialCache.DefaultCredentials;
                }

                options.Headers.Add("Authorization", $"Bearer {api.AccessToken}");
                options.Headers.Add("OsuVersionHash", versionHash);
            });

            if (RuntimeInfo.SupportsJIT && preferMessagePack)
            {
                builder.AddMessagePackProtocol(options =>
                {
                    options.SerializerOptions = SignalRUnionWorkaroundResolver.OPTIONS;
                });
            }
            else
            {
                // eventually we will precompile resolvers for messagepack, but this isn't working currently
                // see https://github.com/neuecc/MessagePack-CSharp/issues/780#issuecomment-768794308.
                builder.AddNewtonsoftJsonProtocol(options =>
                {
                    options.PayloadSerializerSettings.ReferenceLoopHandling = ReferenceLoopHandling.Ignore;
                    options.PayloadSerializerSettings.Converters            = new List <JsonConverter>
                    {
                        new SignalRDerivedTypeWorkaroundJsonConverter(),
                    };
                });
            }

            var newConnection = builder.Build();

            ConfigureConnection?.Invoke(newConnection);

            newConnection.Closed += ex => onConnectionClosed(ex, cancellationToken);
            return(newConnection);
        }
        static async Task Run()
        {
            var connection = new HubConnectionBuilder()
                             .WithUrl("https://transienteventdisplay20180111081216.azurewebsites.net/events")
                             .WithConsoleLogger()
                             .WithMessagePackProtocol()
                             .WithTransport(TransportType.WebSockets)
                             .Build();

            await connection.StartAsync();

            Console.WriteLine("Starting connection. Press Ctrl+C to close.");
            var cts = new CancellationTokenSource();

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

            connection.Closed += e =>
            {
                Console.WriteLine("Connection closed with error: {0}", e);

                cts.Cancel();
                return(Task.CompletedTask);
            };

            await connection.SendAsync("JoinChannel", "default");

            connection.On <string, string, string>("EventPublished",
                                                   async(string category, string eventType, string data) =>
            {
                Console.WriteLine("~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~");
                Console.WriteLine(category);
                Console.WriteLine(eventType);
                Console.WriteLine(data);
            });

            while (true)
            {
                Thread.Sleep(2000);
                // await connection.SendAsync("Send", "alex");
            }
        }
Exemple #4
0
        private static async Task Main(string[] args)
        {
            var downstreams       = new Dictionary <string, TcpClient>();
            var cancellationToken = CancellationToken.None;
            var upstream          = new HubConnectionBuilder()
                                    .WithUrl("http://ec2-35-178-211-187.eu-west-2.compute.amazonaws.com:4000/strider")
                                    .Build();

            upstream.On <RegisterClient>("ClientJoined", async register =>
            {
                var downstream = new TcpClient();
                await downstream.ConnectAsync(IPAddress.Loopback, 25565, cancellationToken);
                downstreams[register.Upstream] = downstream;
                _ = Task.Run(async() =>
                {
                    var stream = downstream.GetStream();
                    var buffer = new byte[4096];
                    while (!cancellationToken.IsCancellationRequested)
                    {
                        var n = await stream.ReadAsync(buffer, cancellationToken);
                        if (n <= 0)
                        {
                            continue;
                        }
                        var tick = new Tick
                        {
                            Destination = register.Upstream,
                            Source      = "Tunnel",
                            Payload     = buffer.Take(n),
                        };
                        await upstream.SendAsync("UpTick", tick, cancellationToken: cancellationToken);
                        await Task.Delay(TimeSpan.FromMilliseconds(1), cancellationToken);
                    }
                }, cancellationToken);
            });
            upstream.On <Tick>("Tick", async tick =>
            {
                downstreams.TryGetValue(tick.Source, out var downstream);
                await downstream !.GetStream().WriteAsync(tick.Payload.ToArray(), cancellationToken);
            });
            await upstream.StartAsync(cancellationToken);

            Console.WriteLine("Press any key to exit");
            Console.ReadKey();
        }
Exemple #5
0
        private static async Task TestAsync()
        {
            string url = "http://localhost:5000/hubs/orders";

            //added package Microsoft.AspNetCore.SignalR.Client

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

            Console.WriteLine("Connecting...");

            await connection.StartAsync();

            Console.WriteLine("Connected.");

            connection.On <Order>("Added", order => Console.WriteLine($"Received {order.Id}"));
        }
        public HubConnection GetInstance(Func <FileContentRequest, Task> requestFileHandler,
                                         Func <Exception, Task> connectionClosedHandler)
        {
            var instance = new HubConnectionBuilder()
                           .WithUrl(GetHubUrl(), ConfigureAuthHttpHeaders)
                           .Build();

            instance
            .On("RequestFile", requestFileHandler);

            instance.KeepAliveInterval =
                TimeSpan.FromSeconds(10);

            instance.Closed +=
                connectionClosedHandler;

            return(instance);
        }
Exemple #7
0
        private static async void StartClient()
        {
            await Task.Delay(10000);

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

            connection.On <string>("Send", data =>
            {
                Console.WriteLine($"Received: {data}");
            });

            await connection.StartAsync();

            await connection.InvokeAsync("Send", "Hello");
        }
        private async Task ConfigurarSignalR(ObservableCollection <Promocao> lista)
        {
            var connection = new HubConnectionBuilder().WithUrl("https://realpromoapiweb.azurewebsites.net/PromoHub").Build();

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

            connection.Closed += async(error) => {
                await Task.Delay(5000);

                await connection.StartAsync();
            };

            await connection.StartAsync();
        }
        public async Task Connect(string host)
        {
            if (Connection != null)
            {
                await Connection.StopAsync();

                await Connection.DisposeAsync();
            }
            Connection = new HubConnectionBuilder()
                         .WithUrl($"{host}/RCDeviceHub")
                         .AddMessagePackProtocol()
                         .WithAutomaticReconnect()
                         .Build();

            ApplyConnectionHandlers();

            await Connection.StartAsync();
        }
Exemple #10
0
        private async Task <HubConnection> CreateConnection(string accessToken = null)
        {
            var hubConnection = new HubConnectionBuilder()
                                .WithUrl($"{Factory.Server.BaseAddress}hubs/main", o =>
            {
                o.HttpMessageHandlerFactory = _ => Factory.Server.CreateHandler();

                if (accessToken != null)
                {
                    o.AccessTokenProvider = () => Task.FromResult(accessToken);
                }
            })
                                .Build();

            await hubConnection.StartAsync();

            return(hubConnection);
        }
Exemple #11
0
        public async Task ConnectAsync(string hostName, int port)
        {
            Connection = new HubConnectionBuilder()
                         .WithUrl($"http://{hostName}:{port}/{Path}")
                         .ConfigureLogging(logging =>
            {
                logging.AddConsole();
            })
                         .Build();

            OnConnectionCreated();

            await Connection.StartAsync();

            initialized = true;

            pingTimer.Change(TimeSpan.Zero, TimeSpan.FromSeconds(10));
        }
Exemple #12
0
        private async Task <HubConnection> ConnectToHubAsync(Action <ParticipantEventArgs> onParticipantChanged, Action <RoomEventArgs> onRoomChanged)
        {
            var connection = new HubConnectionBuilder()
                             .WithUrl(new Uri(_factory.Server.BaseAddress, "voteHub"), opts => opts.HttpMessageHandlerFactory = _ => _factory.Server.CreateHandler())
                             .Build();

            if (onParticipantChanged != null)
            {
                connection.On(nameof(IClient.ParticipantChanged), onParticipantChanged);
            }
            if (onRoomChanged != null)
            {
                connection.On(nameof(IClient.RoomChanged), onRoomChanged);
            }
            await connection.StartAsync();

            return(connection);
        }
        public async Task Run()
        {
            try
            {
                var connection = new HubConnectionBuilder().WithUrl("http://localhost:5000/echo").Build();
                connection.On <string>("echo", _resp => resp.SetResult(_resp));
                await connection.StartAsync();

                await connection.InvokeAsync <string>("echo", message);

                Console.WriteLine(await resp.Task);
            }
            catch (Exception ex)
            {
                Console.Error.WriteLine(ex);
                throw;
            }
        }
Exemple #14
0
        private HubConnection BuildNewHubConnection()
        {
            HubConnection hubConnection = new HubConnectionBuilder()
                                          .WithUrl(SocketHubGateway, (options) => {
                if (!string.IsNullOrEmpty(AccessToken))
                {
                    options.AccessTokenProvider = () => Task.Run(() => AccessToken);
                }
            })
                                          .ConfigureLogging((logging) => {
                logging.AddProvider(new InfallibleLogProvider());
            })
                                          .Build();

            hubConnection.Closed += OnHubConnectionClosed;

            return(hubConnection);
        }
Exemple #15
0
        static async Task Main(string[] args)
        {
            var hubConnection = new HubConnectionBuilder().WithTransport(TransportType.All)
                                .WithUrl("http://localhost:5000/chat?access_token=eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9.eyJodHRwOi8vc2NoZW1hcy54bWxzb2FwLm9yZy93cy8yMDA1LzA1L2lkZW50aXR5L2NsYWltcy9uYW1laWRlbnRpZmllciI6ImpvaG5kb2VAYW50aG9ueWNodS5jYSIsImV4cCI6MTUyNTI0NjcwMCwiaXNzIjoiU2lnbmFsUlRlc3RTZXJ2ZXIiLCJhdWQiOiJTaWduYWxSVGVzdHMifQ.m5HpKWSHsMVuZ2f10QNBfyzBYEevFVRMYxxaLjGK79s")
                                //.WithAccessToken(() => "eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9.eyJodHRwOi8vc2NoZW1hcy54bWxzb2FwLm9yZy93cy8yMDA1LzA1L2lkZW50aXR5L2NsYWltcy9uYW1laWRlbnRpZmllciI6ImFudGhvbnlAYW50aG9ueWNodS5jYSIsImV4cCI6MTUyNTI0MzczNiwiaXNzIjoiU2lnbmFsUlRlc3RTZXJ2ZXIiLCJhdWQiOiJTaWduYWxSVGVzdHMifQ.xGVosVgevMRipSPkE9Z1XU7xsOmoAecIdjgq9NGnC5M")
                                .WithJsonProtocol().Build();

            hubConnection.Closed += e => System.Console.WriteLine(e.ToString());

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

            await hubConnection.StartAsync();

            System.Console.WriteLine("connected!");

            System.Console.ReadLine();
        }
Exemple #16
0
        static async Task Go()
        {
            Console.ReadKey();
            var connection = new HubConnectionBuilder()
                             .WithUrl("https://localhost:5001/chathub")
                             .Build();

            try
            {
                await connection.StartAsync();
            }
            catch (Exception e)
            {
            }
            await connection.InvokeAsync("SendMessage", new { Id = "343" });

            Console.ReadKey();
        }
Exemple #17
0
        private static async Task <HubConnection> ConnectAsync(string url, TextWriter output, CancellationToken cancellationToken = default)
        {
            var connection = new HubConnectionBuilder().WithUrl(url).Build();

            connection.On <string, string>("BroadcastMessage", BroadcastMessage);
            connection.On <string>("Echo", Echo);

            connection.Closed += async(e) =>
            {
                output.WriteLine(e);
                await DelayRandom(200, 1000);
                await StartAsyncWithRetry(connection, output, cancellationToken);
            };

            await StartAsyncWithRetry(connection, output, cancellationToken);

            return(connection);
        }
Exemple #18
0
        static async Task Main(string[] args)
        {
            System.Console.BackgroundColor = ConsoleColor.DarkGray;
            System.Console.ForegroundColor = ConsoleColor.Green;
            System.Console.Title           = "Time";
            var connection = new HubConnectionBuilder().WithUrl("https://localhost:44373/timehub").Build();

            await connection.StartAsync();

            connection.On <string>("updateCurrentTime", (time) => {
                Clear();
                WriteLine(time);
            });

            while (connection.State == HubConnectionState.Connected)
            {
            }
        }
Exemple #19
0
        public async Task <IActionResult> PostGroup(string groupName, [FromBody] MessageViewModel model)
        {
            Console.WriteLine($"ricevuto: {model.Messaggio}");
            var connection = new HubConnectionBuilder()
                             .WithUrl("http://localhost:5001/chat")
                             .WithConsoleLogger()
                             .Build();

            connection.On <string>("Send", data =>
            {
            });

            await connection.StartAsync();

            await connection.InvokeAsync("SendGroup", groupName, model.Messaggio);

            return(Ok());
        }
        static void Main(string[] args)
        {
            Console.WriteLine("Hello World!");

            var conn = new HubConnectionBuilder()
                       .WithUrl("https://localhost:44360/GatewayHub")
                       .AddNewtonsoftJsonProtocol()
                       .Build();

            conn.StartAsync().ConfigureAwait(false);

            conn.On("ReceiveMessage", new Type[] { typeof(object), typeof(object) }, (arg1, arg2) =>
            {
                return(WriteToConsole(arg1));
            }, new object());

            Console.ReadLine();
        }
        public BlazorWebAssemblyBlogNotificationService(NavigationManager navigationManager)
        {
            _navigationManager = navigationManager;

            _hubConnection = new HubConnectionBuilder().AddJsonProtocol(options => {
                options.PayloadSerializerOptions.ReferenceHandler     = System.Text.Json.Serialization.ReferenceHandler.Preserve;
                options.PayloadSerializerOptions.PropertyNamingPolicy = null;
            })
                             .WithUrl(navigationManager.ToAbsoluteUri("/BlogNotificationHub"))
                             .Build();

            _hubConnection.On <BlogPost>("BlogPostChanged", (post) =>
            {
                BlogPostChanged?.Invoke(post);
            });

            _hubConnection.StartAsync();
        }
Exemple #22
0
        static async Task Main(string[] args)
        {
            var IP     = Dns.GetHostEntry("cynthia.ovyno.com").AddressList[0];
            var client = new HubConnectionBuilder()
                         .WithUrl($"http://{IP}:5000/hub/gwent").Build();
            await client.StartAsync();

            Console.WriteLine($"注册结果为{await client.InvokeAsync<bool>("Register", "gezi", "123456", "格子")}");
            try
            {
                Console.WriteLine($"注册结果为{await client.InvokeAsync<bool>("Register", "gezi", "123456", "格子")}");
            }
            catch
            {
                Console.WriteLine("发生了异常");
            }
            Console.ReadLine();
        }
Exemple #23
0
            public SignalRMessageReceiver(string url, string proxy, Guid threadId)
            {
                HubConnection connection = new HubConnectionBuilder()
                                           .WithUrl(url, option =>
                {
                    option.Proxy = new WebProxy(proxy);
                    // Monoのwebsocket実装はproxyがバグっているので除外する。
                    option.Transports = HttpTransportType.ServerSentEvents | HttpTransportType.LongPolling;
                })
                                           .WithAutomaticReconnect()
                                           .Build();


                _connection = connection;
                _threadId   = threadId;

                this.InitReceiveSettings();
            }
Exemple #24
0
        private async Task <HubConnection> CreateAndStartHubConnection()
        {
            // create the hub and specify authentication
            var hubConnection = new HubConnectionBuilder()
                                .WithUrl(_configReader.SignalrHostUrl + "/" + Consts.HubName, opts =>
            {
                opts.AccessTokenProvider = async() =>
                {
                    var token = await GenerateAccessToken();
                    return(token);
                };
            })
                                .Build();

            await hubConnection.StartAsync();

            return(hubConnection);
        }
        public async Task <IActionResult> Index()
        {
            var connection = new HubConnectionBuilder()
                             .WithUrl("http://localhost:5000/chat")
                             .WithConsoleLogger()
                             .Build();

            connection.On <string>("Send2", data =>
            {
                Console.WriteLine($"Received: {data}");
            });

            await connection.StartAsync();

            await connection.InvokeAsync("Send2", "Hello From Index");

            return(View());
        }
Exemple #26
0
        static HubConnection CreateHubConnection(string hubEndpoint, string userId)
        {
            var url        = hubEndpoint.TrimEnd('/') + $"?user={userId}";
            var connection = new HubConnectionBuilder().WithUrl(url).Build();

            connection.On(Target, (string message) =>
            {
                Console.WriteLine($"{userId}: gets message from service: '{message}'");
            });

            connection.Closed += async ex =>
            {
                Console.WriteLine(ex);
                Environment.Exit(1);
            };

            return(connection);
        }
Exemple #27
0
        public async void InitializeSignalR()
        {
            var hubConnection = new HubConnectionBuilder()
                                .WithUrl("https://mini.local/testHub")
                                .WithConsoleLogger()
                                .Build();

            // var hubConnection = new HubConnection("https://mini.local/", false);
            // _hub = hubConnection.CreateHubProxy("testHub");

            _hub = hubConnection;

            _hub.On <string, double>("newUpdate",
                                     (command, state) => ValueChanged?.Invoke(this, new ValueChangedEventArgs(command, state)));


            await _hub.StartAsync();
        }
Exemple #28
0
        public static async Task Main(string[] args)
        {
            string notificationHubUrl = "http://localhost:5000/notificationHub";
            var    connection         = new HubConnectionBuilder()
                                        .WithUrl(notificationHubUrl)
                                        .WithAutomaticReconnect()
                                        .Build();

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

            await connection.StartAsync();

            Console.WriteLine("Press ENTER to exit...");
            Console.ReadLine();
        }
Exemple #29
0
        static void Main(string[] args)
        {
            HubConnection connection;

            //using (var hubConnection = new HubConnection("https://localhost:44390/SubscribeWeather"))
            //{
            //    IHubProxy subscribeHubProxy = hubConnection.CreateHubProxy("SubscribeHub");

            //    subscribeHubProxy.On<WeatherObservation>("WeatherUpdate",
            //        w => Console.WriteLine(
            //            $"WeatherUpdate: Pressure: {w.AirPressure}, Humidity {w.Humidity}, Temperature {w.TemperatureC}, Date {w.Date}"));
            //}


            connection = new HubConnectionBuilder()
                         .WithUrl("http://localhost:53353/ChatHub")
                         .Build();
        }
Exemple #30
0
        private static MultiplayerClient getConnectedClient(int userId)
        {
            var connection = new HubConnectionBuilder()
                             .AddMessagePackProtocol()
                             .WithUrl("http://localhost:80/multiplayer", http => http.Headers.Add("user_id", userId.ToString()))
                             .ConfigureLogging(logging =>
            {
                // logging.AddFilter("Microsoft.AspNetCore.SignalR", LogLevel.Debug);
                // logging.AddConsole();
            })
                             .Build();

            var client = new MultiplayerClient(connection, userId);

            connection.Closed += async error =>
            {
                Console.WriteLine($"Connection closed with error:{error}");

                await connection.StartAsync();
            };

            connection.Reconnected += id =>
            {
                Console.WriteLine($"Connected with id:{id}");
                return(Task.CompletedTask);
            };

            while (true)
            {
                try
                {
                    connection.StartAsync().Wait();
                    break;
                }
                catch
                {
                    // try until connected
                }
            }

            Console.WriteLine($"client {connection.ConnectionId} connected!");

            return(client);
        }