private static async Task MainAsync(string[] args) { Console.WriteLine("Started test client..."); var connection = new HubConnectionBuilder() .WithUrl(HubUrl) .WithAutomaticReconnect() .Build(); try { Console.WriteLine("Starting connection..."); await connection.StartAsync(); Console.WriteLine("Connection started successfully"); // SendAsync just pushes the message, does not wait for an confirmation/ACK from the server // If you want an ACK or a response value, use InvokeAsync instead await connection.SendAsync("BoardUpdate", "Did you get this update?"); } catch (Exception ex) { Console.WriteLine($"Caught exception: {ex.Message}"); } Console.WriteLine("Closing test client"); }
public async Task <Kernel> ConnectKernelAsync(KernelInfo kernelInfo) { // QUESTION: (ConnectKernelAsync) tests? var hubConnection = new HubConnectionBuilder() .WithUrl(HubUrl) .Build(); await hubConnection.StartAsync(); await hubConnection.SendAsync("connect"); var receiver = new KernelCommandAndEventSignalRHubConnectionReceiver(hubConnection); var sender = new KernelCommandAndEventSignalRHubConnectionSender(hubConnection); var proxyKernel = new ProxyKernel(kernelInfo.LocalName, receiver, sender); var _ = proxyKernel.StartAsync(); proxyKernel.RegisterForDisposal(receiver); proxyKernel.RegisterForDisposal(async() => { await hubConnection.DisposeAsync(); }); return(proxyKernel); }
public static void Run([CosmosDBTrigger( databaseName: "Messages", collectionName: "MessagesCollection", ConnectionStringSetting = "CosmosDBConnectionString", LeaseCollectionName = "leases")] IReadOnlyList <Document> input, TraceWriter log) { if (input != null && input.Count > 0) { log.Verbose("Documents modified " + input.Count); log.Verbose("First document Id " + input[0].Id); Task.Factory.StartNew(async() => { string azure = "https://jrsimplemessagessignalr.azurewebsites.net/MessageHub"; HubConnection connection; connection = new HubConnectionBuilder() .WithUrl(azure) .Build(); await connection.StartAsync(); await connection.SendAsync("SendMessage", input[0].GetPropertyValue <string>("key"), input[0]); }); } }
// dotnet add package Microsoft.AspNetCore.SignalR.Client static async Task Main(string[] args) { Console.BackgroundColor = ConsoleColor.Blue; Console.ForegroundColor = ConsoleColor.White; Console.WriteLine("Hello Signal-R Receiver!"); const string url = "http://localhost:5000/signalr/chatter"; HubConnection connection = new HubConnectionBuilder() .WithUrl(url) .Build(); Console.WriteLine("connecting..."); await connection.StartAsync(); Console.WriteLine("Connected."); await connection.SendAsync("JoinRoom", "Klon"); connection.On <ChatMessage>("HaveGotMessage", message => Console.WriteLine($"Received {message.Content}")); Console.WriteLine("Press any key to exit."); Console.ReadKey(); Console.ResetColor(); }
static void Main(string[] args) { //Building the connection to SignalRHub var connection = new HubConnectionBuilder() .WithUrl("http://localhost:5000/ChatHub") .Build(); // Genered a random number between 0 - 100 Random rnd = new Random(); int ID = rnd.Next(100); // Subscribe to the event send to listen to the messages sent connection.On <string>("Send", (message) => { System.Console.WriteLine(message); }); // Stop conecction connection.StartAsync().Wait(); while (true) { System.Console.WriteLine("Type a message:"); // Get input message var message = Console.ReadLine(); // Sending message of one client connection.SendAsync("Send", "Client with ID " + ID + " say: " + message); } }
static void Main(string[] args) { Console.WriteLine("Hub Verbindung wird aufgebaut..."); var url = "http://localhost:63825/chatHub"; var hubConnection = new HubConnectionBuilder() .WithUrl(url).Build(); hubConnection.On <string>("EmpfangeNachricht", msg => EmpfangeNachricht(msg)); hubConnection.StartAsync().Wait(); var running = true; while (running) { Console.WriteLine("Bitte Nachricht eingeben..."); var message = string.Empty; message = Console.ReadLine(); hubConnection.SendAsync("SendMessage", message).Wait(); } }
public async Task Test1() { var connection = new HubConnectionBuilder() .WithUrl("http://localhost:5000/task") .WithConsoleLogger() .WithJsonProtocol() .WithTransport(TransportType.WebSockets) .Build(); await connection.StartAsync(); var fooTask = new FooTask { TaskValue = "Babu", TaskType = "Regular" }; connection.On<string, string>("BroadcastMessage", (x, y) => { }); connection.On<int>("Counter", (x) => { }); await connection.SendAsync("ReceiveTask", new[] { fooTask }); Assert.True(true); }
public override async Task <Kernel> CreateKernelAsync( SignalRConnectionOptions options, KernelInvocationContext context) { var connection = new HubConnectionBuilder() .WithUrl(options.HubUrl) .Build(); await connection.StartAsync(); await connection.SendAsync("connect"); var receiver = new KernelCommandAndEventSignalRHubConnectionReceiver(connection); var sender = new KernelCommandAndEventSignalRHubConnectionSender(connection); var proxyKernel = new ProxyKernel(options.KernelName, receiver, sender); var _ = proxyKernel.RunAsync(); proxyKernel.RegisterForDisposal(receiver); proxyKernel.RegisterForDisposal(async() => { await connection.DisposeAsync(); }); return(proxyKernel); }
// dotnet add package Microsoft.AspNetCore.SignalR.Client static async Task Main(string[] args) { Console.WriteLine("Hello Signal-R Receiver!"); Console.BackgroundColor = ConsoleColor.Blue; Console.ForegroundColor = ConsoleColor.White; const string url = "http://localhost:5000/signalr/alarms"; HubConnection connection = new HubConnectionBuilder() .WithUrl(url) .Build(); await connection.StartAsync(); Console.WriteLine("Connected."); Console.Write("Type unit:"); string unit = Console.ReadLine(); await connection.SendAsync("JoinToUnit", unit); connection.On <string>("Alarm", message => Console.WriteLine($"Received {message}")); connection.On <Command>("Command", command => Console.WriteLine($"Received {command.Title} -> {command.Content}")); Console.WriteLine("Press any key to exit."); Console.ReadKey(); Console.ResetColor(); }
private async Task RunConnection(HttpTransportType transportType) { var userId = "C#" + transportType; _tokens[userId] = GetJwtToken(userId); var hubConnection = new HubConnectionBuilder() .WithUrl(ServerUrl + "/broadcast", options => { options.Transports = transportType; options.AccessTokenProvider = () => _tokens[userId]; }) .Build(); var closedTcs = new TaskCompletionSource(); hubConnection.Closed += e => { closedTcs.SetResult(); return(Task.CompletedTask); }; 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 != HttpTransportType.WebSockets) { _tokens[userId] = GetJwtToken(userId); Console.WriteLine($"[{userId}] Token refreshed"); } } if (ticks % nextMsgAt == 0) { await hubConnection.SendAsync("Broadcast", userId, $"Hello at {DateTime.Now}"); nextMsgAt = Random.Shared.Next(2, 5); } } } catch (Exception ex) { Console.WriteLine($"[{userId}] Connection terminated with error: {ex}"); } }
static async Task Main(string[] args) { const string url = "http://localhost:5000/signalr/customers"; Console.WriteLine("Hello Signal-R Sender!"); HubConnection connection = new HubConnectionBuilder() .WithUrl(url) .WithAutomaticReconnect() .Build(); Console.WriteLine("Connectig..."); await connection.StartAsync(); Console.WriteLine("Connected!"); CustomerFaker customerFaker = new CustomerFaker(); Customer customer = customerFaker.Generate(); Console.WriteLine($"Sending {customer.FirstName} {customer.LastName}"); await connection.SendAsync("SendCustomerAdded", customer); Console.WriteLine("Customer send"); Console.ReadKey(); }
public static async Task Main() { var connection = new HubConnectionBuilder().WithUrl("http://localhost:58295/TrackingHub").Build(); connection.On <Tracking>(TrackingEvents.Receive, message => Console.WriteLine(message.Latitude)); await connection.StartAsync(); double lat = 45; double lng = 16; double spd = 10; while (true) { var t = new Tracking() { Latitude = lat, Longitude = lng, Speed = spd, Timestamp = DateTime.Now }; lat = lat - 0.0001; lng = lat - 0.0001; spd++; await connection.SendAsync("Send", t); Console.ReadLine(); } }
private void ConnectSchedulerNet() { try { var connection = new HubConnectionBuilder() .WithUrl($"{Service}client/?group={Group}") .Build(); OnClose(connection); OnFire(connection); OnWatchCallback(connection); connection.StartAsync().Wait(); connection.SendAsync("Watch", _classNameMapTypes.Keys.ToArray()).Wait(); } catch (Exception e) when(e.InnerException?.InnerException is SocketException) { var exception = (SocketException)e.InnerException.InnerException; if (exception.SocketErrorCode == SocketError.TimedOut || exception.SocketErrorCode == SocketError.ConnectionRefused) { Thread.Sleep(1000); var times = Interlocked.Increment(ref _retryTimes); if (times <= RetryTimes) { Debug.WriteLine("Retry to connect scheduler.net server."); ConnectSchedulerNet(); } } } }
protected override async Task ExecuteAsync(CancellationToken stoppingToken) { while (!stoppingToken.IsCancellationRequested && String.IsNullOrEmpty(Server)) { logger.LogWarning("Server url is not yet set please wait"); await Task.Delay(100, stoppingToken); } while (!stoppingToken.IsCancellationRequested) { var hubConnection = new HubConnectionBuilder() .WithUrl(Server + "/broadcast") .Build(); await hubConnection.StartAsync(); while (!stoppingToken.IsCancellationRequested) { logger.LogInformation("BEGIN Scheduled Update-All"); IEnumerable <CarparkListDTO> carparks = carparkManager.GetCarparks(); foreach (var carpark in carparks) { await hubConnection.SendAsync("NotifyParkingStatusForCarpark", carpark.Id, carparkManager.GetParkingSpots(carpark.Id)); await Task.Delay(1000, stoppingToken); } logger.LogInformation("END Scheduled Update-All, Wait 5000ms for next run"); await Task.Delay(5000, stoppingToken); } } }
private static async Task SignalRClientTestAsync() { string url = "http://localhost:5000/hubs/orders"; // add package Microsoft.AspNetCore.SignalR.Client HubConnection connection = new HubConnectionBuilder() .WithUrl(url) .Build(); Console.WriteLine("Connecting..."); await connection.StartAsync(); Console.WriteLine("Connected."); var orderFaker = new OrderFaker(); while (true) { Order order = orderFaker.Generate(); await connection.SendAsync("AddedOrder", order); Console.WriteLine("Sent order"); // Task.Delay(10); await Task.Delay(TimeSpan.FromSeconds(1)); } }
private static async Task ConnectTestAsync() { Random rand = new Random(); int clientNr = rand.Next(); Console.WriteLine($"Im clientNr: {clientNr}"); string url = "http://localhost:5000/hubs/customers"; //string url = "http://b0b353d8.ngrok.io/hubs/customers"; HubConnection hubConnection = new HubConnectionBuilder() .WithUrl(url, p => p.Headers.Add("Authorization", "Basic YWRtaW46MTIzNA==")) .Build(); Console.WriteLine("Connecting..."); await hubConnection.StartAsync(); Console.WriteLine("Connected."); hubConnection.On <Customer>("AddedCustomer", (c => { Console.WriteLine(c.ToString()); hubConnection.SendAsync("OkGotIt", clientNr); })); hubConnection.On <string>("Cool", (c => Console.WriteLine("Server returned: " + c))); }
static async Task Main(string[] args) { Console.BackgroundColor = ConsoleColor.Green; Console.ForegroundColor = ConsoleColor.White; Console.WriteLine("Hello Signal-R sender!"); const string url = "http://localhost:5000/hubs/customers"; // dotnet add package Microsoft.AspNetCore.SignalR.Client HubConnection connection = new HubConnectionBuilder() .WithUrl(url) .Build(); Console.WriteLine("Connecting..."); await connection.StartAsync(); Console.WriteLine("Connected."); CustomerFaker customerFaker = new CustomerFaker(new AddressFaker()); var customers = customerFaker.GenerateForever(); foreach (var customer in customers) { await connection.SendAsync("CustomerAdded", customer); Console.WriteLine($"Sent {customer.FirstName} {customer.LastName}"); await Task.Delay(TimeSpan.FromSeconds(1)); } Console.ResetColor(); }
public ActionResult ShowTelemetry([FromBody] Telemetry telemetry) { try { #if DEBUG var connection = new HubConnectionBuilder() .WithUrl("https://localhost:44303/chat") //.WithTransport(Microsoft.AspNetCore.Sockets.TransportType.LongPolling) //.WithConsoleLogger() .Build(); #else var connection = new HubConnectionBuilder() .WithUrl("http://signalrapplication.azurewebsites.net/chat") .WithConsoleLogger() .Build(); #endif connection.StartAsync().Wait(); var text = telemetry == null || string.IsNullOrEmpty(telemetry.text) ? "***" : telemetry.text; connection.SendAsync("Send", text).Wait(); // InvokeAsync("Send", text) connection.DisposeAsync().Wait(); return(Json("Success")); } catch (Exception ex) { return(Json($"Exception {ex.Message}")); } }
protected override async Task ExecuteAsync(CancellationToken stoppingToken) { // dotnet add package Microsoft.AspNetCore.SignalR.Client HubConnection connection = new HubConnectionBuilder() .WithUrl(url, options => { options.Headers.Add("Grupa", "GrupaA"); }) .Build(); _logger.LogInformation("Connecting..."); await connection.StartAsync(); _logger.LogInformation("Connected."); connection.On <Customer>("Created", customer => _logger.LogInformation($"Received {customer.FirstName}")); while (!stoppingToken.IsCancellationRequested) { _logger.LogInformation("Worker running at: {time}", DateTimeOffset.Now); var customer = customerFaker.Generate(); _logger.LogInformation("Sending {customer} at: {time}", customer.FullName, DateTimeOffset.Now); await connection.SendAsync("CreatedCustomer", customer); _logger.LogInformation("Sent {customer} at: {time}", customer.FullName, DateTimeOffset.Now); await Task.Delay(1000, stoppingToken); } }
static async Task Main(string[] args) { await Task.Delay(3000); var connection = new HubConnectionBuilder() .WithUrl("http://localhost:5005/sockethub", options => { options.Headers["Application"] = "API Receive"; }) .WithAutomaticReconnect() .Build(); await connection.StartAsync(); await connection.SendAsync("UpdateClient", "Client 6"); Console.WriteLine("Connection started."); connection.On <string, string>("ReceiveGenericEvent", async(id, runningTime) => { await ReceiveAsync(id, runningTime); }); connection.Closed += async(error) => { await Task.Delay(new Random().Next(0, 5) * 1000); await connection.StartAsync(); }; Console.ReadLine(); }
// dotnet add package Microsoft.AspNetCore.SignalR.Client static async Task Main(string[] args) { Console.WriteLine("Hello Signal-R Sender!"); Console.BackgroundColor = ConsoleColor.Green; Console.ForegroundColor = ConsoleColor.White; const string url = "http://localhost:5000/signalr/alarms"; HubConnection connection = new HubConnectionBuilder() .WithUrl(url) .WithAutomaticReconnect() .Build(); await connection.StartAsync(); // dotnet add package Bogus IEnumerable <Command> commands = new Faker <Command>() .RuleFor(p => p.Title, f => f.Lorem.Sentence()) .RuleFor(p => p.Content, f => f.Lorem.Paragraph()) .GenerateForever(); Console.WriteLine("Connected."); Console.Write("Type unit:"); string unit = Console.ReadLine(); await connection.SendAsync("JoinToUnit", unit); foreach (Command command in commands) { // await connection.SendAsync("SendAlarm", "Fire!"); command.ToUnit = unit; await connection.SendAsync("SendCommand", command); Console.WriteLine($"Sent command {command.Title}"); await Task.Delay(TimeSpan.FromSeconds(1)); } Console.WriteLine("Press any key to exit."); Console.ReadKey(); Console.ResetColor(); }
static async Task Main(string[] args) { ServicePointManager .ServerCertificateValidationCallback += new RemoteCertificateValidationCallback(ValidateCertificate); HttpClient httpClient = new HttpClient(); Console.Write("Username: "******"Password: "******""; while (true) { var key = Console.ReadKey(intercept: true); if (key.Key == ConsoleKey.Enter) { break; } password += key.KeyChar; } ServicePointManager.ServerCertificateValidationCallback += new System.Net.Security .RemoteCertificateValidationCallback(ValidateCertificate); var hubConnection = new HubConnectionBuilder() .WithUrl($"{baseUrl}/chat", options => { options.AccessTokenProvider = async() => { var stringData = JsonConvert.SerializeObject(new { username, password }); var content = new StringContent(stringData); content.Headers.ContentType = new MediaTypeHeaderValue("application/json"); var response = await httpClient.PostAsync( $"{ baseUrl }/api/token", content); response.EnsureSuccessStatusCode(); return(await response.Content.ReadAsStringAsync()); }; }) .Build(); hubConnection.On <string, string>("newMessage", (sender, message) => Console.WriteLine($"{sender}: {message}")); await hubConnection.StartAsync(); System.Console.WriteLine("\nConnected!"); while (true) { var message = Console.ReadLine(); await hubConnection.SendAsync("SendMessage", message); } }
public static async Task <int> ExecuteAsync(string baseUrl) { baseUrl = string.IsNullOrEmpty(baseUrl) ? "http://localhost:53042/chat" : baseUrl; var loggerFactory = new LoggerFactory(); var logger = loggerFactory.CreateLogger <Program>(); Console.WriteLine($"Connecting to {baseUrl}..."); var connection = new HubConnectionBuilder() .WithUrl(baseUrl) .WithConsoleLogger() .Build(); //var connection = new HttpConnection(new Uri(baseUrl), loggerFactory); try { var cts = new CancellationTokenSource(); connection.On <string>("Send", Connection_MessageReceived); connection.Closed += e => { return(Task.CompletedTask); }; await connection.StartAsync(); Console.WriteLine($"Connected to {baseUrl}"); Console.CancelKeyPress += (sender, a) => { a.Cancel = true; cts.Cancel(); }; while (!cts.Token.IsCancellationRequested) { var line = await Task.Run(() => Console.ReadLine(), cts.Token); if (line == null) { break; } await connection.SendAsync("Send", cts.Token, line); } } catch (AggregateException aex) when(aex.InnerExceptions.All(e => e is OperationCanceledException)) { } catch (OperationCanceledException) { } finally { await connection.DisposeAsync(); } return(0); }
static void Main(string[] args) { Console.Write("User name: "); var userName = Console.ReadLine(); Console.Write("Password: "******"{baseUrl}/chat", options => { options.AccessTokenProvider = async() => { var stringData = JsonConvert.SerializeObject(new { userName, password }); var content = new StringContent(stringData); content.Headers.ContentType = new MediaTypeHeaderValue("application/json"); var response = await _httpClient.PostAsync($"{ baseUrl }/api/token", content); response.EnsureSuccessStatusCode(); return(await response.Content.ReadAsStringAsync()); }; }) .Build(); hubConnection.On <string, string>("newMessage", (sender, message) => Console.WriteLine($"{sender}: {message}")); hubConnection.StartAsync().Wait(); System.Console.WriteLine("\nConnected!"); while (true) { var message = Console.ReadLine(); if (message.Equals("exit")) { break; } hubConnection.SendAsync("SendMessage", message).Wait(); } System.Console.WriteLine("\nDisonnecting ..."); }
private static async Task StreamLoremIpsum(int index, ILogger logger, string signalRUrl) { index++; var connection = new HubConnectionBuilder() .WithUrl(signalRUrl) .Build(); async Task OnConnectionOnClosed(Exception error) { logger.LogError(error, "Hub connection error."); logger.LogWarning($"Client #{index}. connection was closed. Restarting..."); await Task.Delay(new Random().Next(0, 5) * 1000); await connection.StartAsync(); } connection.Closed += OnConnectionOnClosed; await connection.StartAsync(); logger.LogInformation($"Client #{index}. connection opened..."); async IAsyncEnumerable <string> ClientStreamData() { using (var loremIpsumStream = new DevTest.LorumIpsumStream()) { using (var streamReader = new StreamReader(loremIpsumStream, Encoding.Unicode, true)) { string text = null, leftOvers = null; do { var data = await ReadUntilNextSpace(streamReader); if (!string.IsNullOrWhiteSpace(data.text)) { // it would be easier if source stream allowed seeking, but we can workaround that issue. text = leftOvers + data.text; leftOvers = data.leftOvers; //going to be appended logger.LogDebug( $"Client {index}. Fetched data from the stream: {text}. Sending to the server"); yield return(text); await Task.Delay(1000); } } while (!string.IsNullOrWhiteSpace(text)); if (!string.IsNullOrWhiteSpace(leftOvers)) { yield return(leftOvers); } } } } await connection.SendAsync("UploadLoremIpsumStream", ClientStreamData()); }
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}"); } }
static async Task Main(string[] args) { Console.BackgroundColor = ConsoleColor.DarkBlue; Console.ForegroundColor = ConsoleColor.White; Console.WriteLine("Hello Signal-R Sender!"); const string url = "http://localhost:5030/signalr/messages"; // dotnet add package Microsoft.AspNetCore.SignalR.Client HubConnection connection = new HubConnectionBuilder() .WithUrl(url) .Build(); Console.WriteLine("Connecting..."); await connection.StartAsync(); Console.WriteLine("Connected."); IEnumerable <Message> messages = new Faker <Message>() .RuleFor(p => p.Title, f => f.Lorem.Sentence()) .RuleFor(p => p.Content, f => f.Lorem.Paragraph()) .GenerateForever(); string[] units = new string[] { "UnitA", "UnitB" }; Random random = new Random(); foreach (var message in messages) { //Message message = new Message //{ // Title = "Hello Signal-R!", // Content = "Signal-R is awesome!" }; // await connection.SendAsync("SendMessage", message); string unit = units[random.Next() % 2]; await connection.SendAsync("SendMessageToUnit", message, unit); Console.WriteLine($"Sent {message.Title} to [{unit}]"); await Task.Delay(TimeSpan.FromSeconds(1)); } Console.WriteLine("Press any key to exit."); Console.ReadKey(); Console.ResetColor(); }
static async Task Main(string[] args) { Console.WriteLine("WebDay 2021 - SignalR : Fake Sensor Console"); var sensorId = Guid.NewGuid(); Console.WriteLine($"SensorId: {sensorId}"); await using var hubConnection = new HubConnectionBuilder() .WithAutomaticReconnect() .WithUrl("https://localhost:44391/sensorhub") .Build(); await hubConnection.StartAsync(); await hubConnection.SendAsync("ConnectSensor", sensorId.ToString()); Console.CancelKeyPress += new ConsoleCancelEventHandler(async(sender, args) => { await hubConnection.SendAsync("DisconnectSensor", sensorId.ToString()); await hubConnection.StopAsync(); Console.WriteLine("\nThe publish operation has been interrupted."); }); Console.WriteLine("\nPress CRTL+C to exit..."); var random = new Random(); while (true) { var measure = random.Next(20, 22) + random.NextDouble(); await hubConnection.SendAsync("PushSensorMeasurements", sensorId, measure); Console.WriteLine($"Pushed: {measure}"); await Task.Delay(1000); } }
private static async Task MainAsync(CancellationToken cancellationToken) { //Console.Out.WriteAsync("passou????"); var hubConnection = new HubConnectionBuilder() .WithUrl("http://localhost:60672/iot") .Build(); //CancellationToken disconnectedToken = Response.ClientDisconnectedToken; //using (var source = CancellationTokenSource.CreateLinkedTokenSource(cancellationToken, disconnectedToken)) await hubConnection.StartAsync(); // Esse será o ponto no qual irá alimentar o servidor com os dados coletados no mongodb MongoDBContext dBContext = new MongoDBContext(); // colocar filtro de últimos 5 minutos de coleta List <IotData> listaVal = dBContext.IotData.Find(m => true).SortByDescending(e => e.datetime).Limit(100).ToList(); // preparar os dados List <JsonClass> listback = new List <JsonClass>(); foreach (var foo in listaVal) { listback.Add( new JsonClass { pitch = foo.pitch, pitch_median = foo.pitch_median, yam = foo.yam, yam_median = foo.yam_median, roll = foo.roll, roll_median = foo.roll_median } ); } //Console.WriteLine(listback); while (!cancellationToken.IsCancellationRequested) { await Task.Delay(2000, cancellationToken); // Finally send the value: await hubConnection.SendAsync("Broadcast", "data", listback, cancellationToken); } await hubConnection.DisposeAsync(); }
static async Task Main(string[] args) { System.Console.WriteLine("Hello World!"); HubConnection hubConnection = new HubConnectionBuilder().WithUrl("http://localhost:5000/hub").Build(); await hubConnection.StartAsync(); await hubConnection.SendAsync("RegisterServer", Dns.GetHostName()); hubConnection.On <string>("AddServerConfig", x => { System.Console.WriteLine(x); }); // var client = new System.Net.HttpClient { B} System.Console.Read(); }