public async Task Can_connect_via_proxy() { using (var signalRServer = BuildSignalRServerOnRandomPort(_outputHelper)) { await signalRServer.StartAsync(); var signalRPort = signalRServer.GetServerPort(); using (var proxyServer = BuildWebSocketProxyServerOnRandomPort(signalRPort, _outputHelper)) { await proxyServer.StartAsync(); var proxyPort = proxyServer.GetServerPort(); // Connection directly to SignalR Server var directConnection = new HubConnectionBuilder() .WithUrl($"http://localhost:{signalRPort}/ping") .ConfigureLogging(logging => logging .AddDebug() .AddProvider(new XunitLoggerProvider(_outputHelper, "connection-direct"))) .Build(); directConnection.Closed += async error => { _outputHelper.WriteLine("connection-direct error: " + error.ToString()); }; await directConnection.StartAsync(); // Callback when On var messageRecieved = new TaskCompletionSource <bool>(); directConnection.On("OnPing", () => { messageRecieved.SetResult(true); }); // Connect to SignalR Server via proxy var proxyConnection = new HubConnectionBuilder() .WithUrl($"http://localhost:{proxyPort}/ping") .ConfigureLogging(logging => logging .AddDebug() .AddProvider(new XunitLoggerProvider(_outputHelper, "connection-proxy"))) .Build(); proxyConnection.Closed += async error => { _outputHelper.WriteLine(error.ToString()); }; await proxyConnection.StartAsync(); // Send message to all clients await proxyConnection.InvokeAsync("PingAll"); messageRecieved.Task.Wait(TimeSpan.FromSeconds(3)).ShouldBeTrue(); messageRecieved.Task.Result.ShouldBeTrue(); } } }
private async Task RunConnection(TransportType transportType) { var userId = "C#" + transportType.ToString(); _tokens[userId] = await GetJwtToken(userId); var hubConnection = new HubConnectionBuilder() .WithUrl(ServerUrl + "/broadcast") .WithTransport(transportType) .WithJwtBearer(() => _tokens[userId]) .Build(); var closedTcs = new TaskCompletionSource <object>(); hubConnection.Closed += e => closedTcs.SetResult(null); hubConnection.On <string, string>("Message", (sender, message) => Console.WriteLine($"[{userId}] {sender}: {message}")); await hubConnection.StartAsync(); Console.WriteLine($"[{userId}] Connection Started"); var ticks = 0; var nextMsgAt = 3; try { while (!closedTcs.Task.IsCompleted) { await Task.Delay(1000); ticks++; if (ticks % 15 == 0) { // no need to refresh the token for websockets if (transportType != TransportType.WebSockets) { _tokens[userId] = await GetJwtToken(userId); Console.WriteLine($"[{userId}] Token refreshed"); } } if (ticks % nextMsgAt == 0) { await hubConnection.SendAsync("Broadcast", userId, $"Hello at {DateTime.Now.ToString()}"); nextMsgAt = _random.Next(2, 5); } } } catch (Exception ex) { Console.WriteLine($"[{userId}] Connection terminated with error: {ex}"); } }
public async Task HubContextHack() { var webHostBuilder = new WebHostBuilder() .ConfigureServices(services => { services.AddSignalR(); }) .Configure(app => { app.UseSignalR(routes => routes.MapHub <StrongEchoHub>("/echo")); }); var server = new TestServer(webHostBuilder); var connection = new HubConnectionBuilder() .WithUrl("http://localhost/echo", o => o.HttpMessageHandlerFactory = _ => server.CreateHandler()) .Build(); var hubContextMsg = string.Empty; var hubMsg = string.Empty; connection.On <string>("OnMessageRecievedFromHubContext", msg => { hubContextMsg = msg; }); connection.On <string>("OnMessageRecievedFromHub", msg => { hubMsg = msg; }); await connection.StartAsync(); var message = "Integration Testing in Microsoft AspNetCore SignalR"; var hubContext = server.Host.Services.GetService <IHubContext <StrongEchoHub, IStrongEchoHub> >(); await hubContext.Clients.All.OnMessageRecievedFromHubContext(message); await connection.InvokeAsync("SendFromHub", "blah " + message); hubContextMsg.Should().Be(message); hubMsg.Should().Be("blah " + message); }
static async Task Main(string[] args) { var connection = new HubConnectionBuilder() .WithUrl("https://localhost:5001/monitorhub?appid=SenseNet") .Build(); connection.Closed += async error => { await Task.Delay(new Random().Next(0, 5) * 1000); await connection.StartAsync(); }; connection.On <SnTaskEvent>("onTaskEvent", taskEvent => { Console.WriteLine($"Agent: {taskEvent.Agent}, " + $"Event: {taskEvent.EventType}, Title: {taskEvent.Title}"); }); connection.On <string, SnHealthRecord>("heartbeat", (agentName, healthRecord) => { Console.WriteLine($"HEARTBEAT Agent: {agentName}, RAM: {healthRecord.RAM}"); }); connection.On <SnProgressRecord>("writeProgress", progressRecord => { Console.WriteLine($"PROGRESS {progressRecord.Progress.SubtaskProgress}, " + $"Details: {progressRecord.Progress.Details}"); }); try { Console.WriteLine("Connecting to server..."); await connection.StartAsync(); Console.WriteLine("Monitor started."); } catch (Exception ex) { Console.WriteLine($"Error: {ex.Message}"); } Console.ReadLine(); }
public static void ConnectToNode(string address) { HubConnection connection = new HubConnectionBuilder() .WithUrl(address + "/chain") .Build(); connection.On <string>("Blockchain", (chain) => { _blockchain = JsonConvert.DeserializeObject <Chain>(chain); }); connection.On <Block>("Block", (block) => { _blockchain.AddBlock(block); }); connection.StartAsync().Wait(); _nodes.Add(connection); }
public async Task <bool> ConnectNotificationsAsync(Func <FilePublishedNotification, Task> filePublishedHandler) { if (LoggedInUser == null) { return(false); } try { var hr = await apiService.NotificationsConnectSignalR(new SignalRHubConnectNotificationRequest { }, authToken.ToString(), userId.ToString()); if (string.IsNullOrWhiteSpace(hr.AccessToken) || string.IsNullOrWhiteSpace(hr.Url)) { return(false); } hub = new HubConnectionBuilder().WithUrl(hr.Url, options => { options.AccessTokenProvider = () => { return(Task.FromResult(hr.AccessToken)); }; }) .Build(); hub.On <byte[]>("OnFilePublished", b => { var n = FilePublishedNotification.FromBytes(b); if (n != null) { _ = filePublishedHandler(n); } }); await hub.StartAsync(); return(true); } catch { try { await hub.DisposeAsync(); } catch { } finally { hub = null; } } return(false); }
static void Main() { var connection = new HubConnectionBuilder() .WithUrl("https://*****:*****@"{0} / {1}", message, username); }); Console.ReadKey(); }
private static async Task <HubConnection> ConnectAsync(string url) { var writer = Console.Out; var connection = new HubConnectionBuilder().WithUrl(url + "/chat").Build(); connection.Closed += async(e) => { Console.WriteLine(e); await Task.Delay(new Random().Next(0, 5) * 1000); await connection.StartAsync(); }; connection.On <string, string>("BroadcastMessage", BroadcastMessage); connection.On <string>("Echo", Echo); await connection.StartAsync(); return(connection); }
static void Main() { Console.WriteLine("Press a key to start listening.."); Console.ReadKey(); try { var builder = new ConfigurationBuilder().SetBasePath(Directory.GetCurrentDirectory()) .AddJsonFile("appsettings.json"); var configuration = builder.Build(); var url = configuration["hostUrl"]; var connection = new HubConnectionBuilder() .WithUrl(url, (opts) => { opts.HttpMessageHandlerFactory = (message) => { if (message is HttpClientHandler clientHandler) { // bypass SSL certificate clientHandler.ServerCertificateCustomValidationCallback += (sender, certificate, chain, sslPolicyErrors) => { return(true); } } ; return(message); }; }) .Build(); var clientInfo = new ConnectedClient { AppName = "Biokit", AppVersion = "1.0" }; connection.On <ConnectedClient>("UpdateClientInfo", (client) => { clientInfo.ConnectionId = client.ConnectionId; Console.WriteLine(clientInfo); }); connection.StartAsync().GetAwaiter().GetResult(); connection.InvokeAsync("GetAppInfo", clientInfo).GetAwaiter().GetResult(); } catch (Exception ex) { Console.WriteLine(ex.Message); } Console.WriteLine("Listening..... Press a key to quit"); Console.ReadKey(); }
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}'"); }); return(connection); }
public void RegisterEvent() { // Mở kết nối đến server // Ta chỉ mở kết nối một lần duy nhất trong toàn bộ chương trình HubConnection = new HubConnectionBuilder().WithUrl("http://localhost:4444").Build(); HubConnection.StartAsync(); // Đăng ký lắng nghe sự kiện ReceiveMessage từ server với một tham số kiểu chuỗi Action <string> actionMessage = new Action <string>(GetMessage); HubConnection.On <string>("ReceiveMessage", actionMessage); // Đăng ký lắng nghe sự kiện ABC từ server với 2 tham số // một tham số kiểu int và một tham số kiểu string // Lần này ta viết kiểu hàm vô danh HubConnection.On <int, string>("ABC", (aNumber, aString) => { Console.WriteLine("I just got something from the server," + "a number and a string. They are: " + aNumber + " and " + aString); }); }
static private void BasicClient(int id) { bool disconnect = false; bool connected = false; try { var connection = new HubConnectionBuilder(). WithUrl(SignalRTestClient.huburl).Build(); connection.ServerTimeout = new TimeSpan(0, 1, 0); connection.On <string, string>("Send", (ticket, state) => { SignalRTestClient.msgRecievedCount++; Write(" Message recieved: " + ticket + " " + state); StopConn(connection).Wait(); }); try { StartConn(connection).Wait(); Write(id + " Connected"); connected = true; } catch (Exception ex) { Write(id + " Connection failed " + ex.Message); } if (connected) { SendMsg(connection, "joinGroup", SignalRTestClient.hubGroup, id).Wait(); connection.Closed += async(error) => { Write(" Connection closed: " + error); connected = false; SignalRTestClient.connectionsCount--; Write("ConnectionsCount: " + SignalRTestClient.connectionsCount); if (!disconnect) { await Task.Delay(new Random().Next(0, 5) * 1000); StartConn(connection).Wait(); SendMsg(connection, "joinGroup", SignalRTestClient.hubGroup, id).Wait(); } }; } } catch (Exception ex) { Write(id + " Disconnected : " + ex.Message); disconnect = true; } }
private static async Task <HubConnection> ConnectAsync(string url, TextWriter output, CancellationToken cancellationToken = default) { var connection = new HubConnectionBuilder() .WithUrl(url) .AddMessagePackProtocol().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); }
static void Main(string[] args) { Console.WriteLine("Press a key to start listening.."); Console.ReadKey(); var connection = new HubConnectionBuilder() .WithUrl("https://localhost:44362/coffeehub") .AddMessagePackProtocol() .Build(); connection.On <Order>("NewOrder", (order) => Console.WriteLine($"Somebody ordered an {order.Product}")); connection.On <string>("ReceiveOrderUpdate", (update) => Console.WriteLine($"Status: {update}")); connection.StartAsync().GetAwaiter().GetResult(); Console.WriteLine("Listening. Press a key to quit"); Console.ReadKey(); }
static void Main(string[] args) { var connection = new HubConnectionBuilder().WithUrl("http://localhost:5000/notification").Build(); connection.StartAsync().Wait(); connection.InvokeAsync("SendMessage", "eswar", "Hello World"); connection.On("ReceiveMessage", (string message) => { Console.WriteLine(message); }); Console.ReadLine(); }
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); }); }); await connection.StartAsync(); }
static void Main(string[] args) { var connection = new HubConnectionBuilder() .WithUrl("http://localhost:5000/hub") .Build(); connection.On <string>("message", message => { Console.WriteLine($"signalr: {message}"); }); connection.StartAsync().Wait(); connection.InvokeAsync("SendMessage", "1234", "some message").Wait(); }
//Connent SignalR public async Task <IActionResult> Index() { try { var name = User.Claims.First(x => x.Type == NetConnectClaims.Name).Value; var lastname = User.Claims.First(x => x.Type == NetConnectClaims.Lastname).Value; var userId = User.Claims.First(x => x.Type == NetConnectClaims.UserId).Value; var hubUrl = "https://localhost:44317/chat"; var hubConnection = new HubConnectionBuilder() .WithUrl(hubUrl, options => { options.Transports = Microsoft.AspNetCore.Http.Connections.HttpTransportType.WebSockets; options.Headers = options.Headers = new Dictionary <string, string>() { { NetConnectClaims.UserId, userId }, { NetConnectClaims.Name, name } };; }) .Build(); var closedTcs = new TaskCompletionSource <object>(); hubConnection.Closed += e => { closedTcs.SetResult(null); return(Task.CompletedTask); }; hubConnection.On <string, string>("broadcastMessage", (sender, message) => InvokeMessage(sender, message)); //Connect await hubConnection.StartAsync(); ////Send Message //await hubConnection.InvokeAsync("Send", "test message"); ////Disconnecct //await hubConnection.DisposeAsync().ContinueWith(t => //{ // if (t.IsFaulted) // Console.WriteLine(t.Exception.GetBaseException()); // else // Console.WriteLine("Disconnected"); //}); } catch (Exception ex) { } return(View()); }
public static async Task InicializaAsync() { var connection = new HubConnectionBuilder() .WithUrl("http://localhost:7354/sync", options => { options.AccessTokenProvider = GetToken; }) .Build(); connection.On <Inscricao>("InscricaoChanged", AtualizaInscricao); connection.On <Confirmacao>("ConfirmacaoChanged", AtualizaConfirmacao); connection.Closed += async error => { await Task.Delay(1000); await connection.StartAsync(); }; await connection.StartAsync(); }
public async Task StartAsync(CancellationToken cancellationToken = default) { cancellationToken.Register(() => resp.TrySetCanceled()); var connection = new HubConnectionBuilder().WithUrl("http://localhost:5000/echo").Build(); connection.On <string>("echo", _resp => resp.TrySetResult(_resp)); await connection.StartAsync(cancellationToken); await connection.InvokeAsync <string>("echo", message, cancellationToken); Console.WriteLine(await resp.Task); }
static async Task Main(string[] args) { Console.BackgroundColor = ConsoleColor.DarkGreen; Console.ForegroundColor = ConsoleColor.White; Console.WriteLine("Hello Signal-R Receiver!"); const string url = "http://localhost:5000/signalr/messages"; // dotnet add package Microsoft.AspNetCore.SignalR.Client HubConnection connection = new HubConnectionBuilder() .WithUrl(url) .WithAutomaticReconnect(new[] { TimeSpan.Zero, TimeSpan.FromSeconds(5), TimeSpan.FromSeconds(10), TimeSpan.FromSeconds(30) }) .Build(); connection.Reconnecting += error => { if (connection.State == HubConnectionState.Reconnecting) { Console.WriteLine("Próba połączenia..."); } return(Task.CompletedTask); }; connection.Reconnected += error => { if (connection.State == HubConnectionState.Connected) { Console.WriteLine("Connected again."); } return(Task.CompletedTask); }; connection.Closed += Connection_Closed; connection.Closed += ByeBye; connection.On <string>("YouHaveGotMessage", message => Console.WriteLine($"Received {message}")); Console.WriteLine("Connecting..."); await connection.StartAsync(); Console.WriteLine("Connected."); Console.WriteLine("Press any key to exit."); Console.ReadKey(); Console.ResetColor(); }
static async Task Main(string[] args) { var connection = new HubConnectionBuilder() .WithUrl("http://localhost:5000/chat") .WithMessagePackProtocol() .WithConsoleLogger() .Build(); var cts = new CancellationTokenSource(); Console.CancelKeyPress += (sender, e) => { e.Cancel = true; cts.Cancel(); }; connection.Closed += e => { cts.Cancel(); return(Task.CompletedTask); }; connection.On <string>("Send", data => { Console.WriteLine($"Server: {data}"); }); await connection.StartAsync(); var cancelledTask = Task.Delay(-1, cts.Token); while (!cts.IsCancellationRequested) { Console.Write("Client: "); var task = await Task.WhenAny(cancelledTask, Task.Run(() => Console.ReadLine())); if (task is Task <string> readline) { var line = await readline; await connection.InvokeAsync("Send", line); } else { break; } } await connection.DisposeAsync(); cts.Dispose(); }
static void Main(string[] args) { Console.WriteLine("Service started"); InitializeIoc(); var requestResults = GetCurrentRequest(); foreach (var result in requestResults) { var info = new WeatherForecastDto() { City = result.RequestedCity, DailyTemperature = new Temperature() { Highest = result.DailyHighestTemp, Lowest = result.DailyLowestTemp }, WeeklyTemperature = new Temperature() { Highest = result.WeeklyHighestTemp, Lowest = result.WeeklyLowestTemp } }; var serializedResult = JsonConvert.SerializeObject(info); Console.WriteLine("PreviousRequests:"); Console.WriteLine(serializedResult); } HubConnection connection = new HubConnectionBuilder() .WithUrl("http://localhost:64368/serverhub") .WithAutomaticReconnect() .Build(); connection.Closed += async(error) => { await Task.Delay(new Random().Next(0, 5) * 1000); await connection.StartAsync(); }; connection.StartAsync(); connection.On <string, string>("ReceiveMessage", (string elapsedTime, string message) => { Console.WriteLine("New Service Request: "); Console.WriteLine($"Total Time Elapsed: {elapsedTime} - Service Message : {message}"); }); Console.ReadLine(); }
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(); }
protected override async Task OnAfterRenderAsync(bool render) { if (render) { Balance = new HubConnectionBuilder().WithUrl(Manager.ToAbsoluteUri("/hub/balance")).Build(); Hermes = new HubConnectionBuilder().WithUrl(Manager.ToAbsoluteUri("/hub/hermes")).Build(); Balance.On <Catalog.Models.Balance>("ReceiveBalanceMessage", (balance) => StateHasChanged(balance)); Hermes.On <Catalog.Models.Message>("ReceiveCurrentMessage", (current) => StateHasChanged(current)); await Balance.StartAsync(); await Hermes.StartAsync(); } }
private static async Task HandleSignalRConfiguration(string baseUrl) { var connection = new HubConnectionBuilder() .WithUrl($"{baseUrl}/messagesHub") .Build(); connection.On <string, string>("BroadcastMessageSentAction", (to, sentMessageIdentifier) => { Console.WriteLine($"Message to {to} with identifier: {sentMessageIdentifier} was sent successfully. :-)"); }); await connection.StartAsync(); }
static void Main(string[] args) { var connection = new HubConnectionBuilder() .WithUrl("http://localhost:62710/SimulatedLongRunningTaskHub") .AddMessagePackProtocol() .Build(); connection.On <string>("ReceiveTaskStatus", (message) => { Console.WriteLine(message); }); connection.StartAsync().GetAwaiter().GetResult(); Console.WriteLine("Listening..."); Console.ReadLine(); }
static void Main(string[] args) { var connection = new HubConnectionBuilder().WithUrl("http://192.168.10.33:6061/NotificationHub").Build(); connection.StartAsync().Wait(); connection.InvokeCoreAsync("CreateNotification", args: new[] { "2" }); connection.On("GetNotification", (int userId) => { using var client = new HttpClient(); var result = client.GetAsync("http://192.168.10.33:6060/api/notification/notifications"); Console.WriteLine(result.Status); }); }
async Task ConnectToHub() { var connection = new HubConnectionBuilder() .WithUrl(URL) .Build(); connection.On <short>("OnSamplePlayed", (channel) => { SendNoteOnMessage(channel); }); await connection.StartAsync(); }
public async void Initialized() { this.Notifications = new ObservableCollection <string>(); var hubConnection = new HubConnectionBuilder() .WithUrl(UrlBuilder.BuildEndpoint("Notifications")) .Build(); hubConnection.On <string>("ReciveServerUpdate", update => { //todo }); await hubConnection.StartAsync(); }