From 2d278009b253f3e2e5a1b8bfa61cf3918e414e11 Mon Sep 17 00:00:00 2001 From: Andrew Stanton-Nurse Date: Tue, 18 Apr 2017 12:41:23 -0700 Subject: [PATCH] clean up client sample (#392) --- samples/ClientSample/ClientSample.csproj | 1 + samples/ClientSample/HubSample.cs | 47 ++++++++++---- samples/ClientSample/Program.cs | 46 ++++++++++++- samples/ClientSample/RawSample.cs | 65 ++++++++++--------- .../EndPoints/MessagesEndPoint.cs | 4 +- samples/SocketsSample/Program.cs | 12 ++-- samples/SocketsSample/SocketsSample.csproj | 4 +- samples/SocketsSample/Startup.cs | 4 +- .../ConnectionManager.cs | 2 +- 9 files changed, 126 insertions(+), 59 deletions(-) diff --git a/samples/ClientSample/ClientSample.csproj b/samples/ClientSample/ClientSample.csproj index 1bd801900c..53645b78b9 100644 --- a/samples/ClientSample/ClientSample.csproj +++ b/samples/ClientSample/ClientSample.csproj @@ -16,6 +16,7 @@ + diff --git a/samples/ClientSample/HubSample.cs b/samples/ClientSample/HubSample.cs index ff89b1d3a3..049e20551d 100644 --- a/samples/ClientSample/HubSample.cs +++ b/samples/ClientSample/HubSample.cs @@ -2,40 +2,48 @@ // Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information. using System; +using System.Linq; using System.Threading; using System.Threading.Tasks; using Microsoft.AspNetCore.SignalR; using Microsoft.AspNetCore.SignalR.Client; +using Microsoft.Extensions.CommandLineUtils; using Microsoft.Extensions.Logging; namespace ClientSample { internal class HubSample { - public static async Task MainAsync(string[] args) + internal static void Register(CommandLineApplication app) { - var baseUrl = "http://localhost:5000/hubs"; - if (args.Length > 0) + app.Command("hub", cmd => { - baseUrl = args[0]; - } + cmd.Description = "Tests a connection to a hub"; + + var baseUrlArgument = cmd.Argument("", "The URL to the Chat Hub to test"); + + cmd.OnExecute(() => ExecuteAsync(baseUrlArgument.Value)); + }); + } + + public static async Task ExecuteAsync(string baseUrl) + { + baseUrl = string.IsNullOrEmpty(baseUrl) ? "http://localhost:5000/hubs" : baseUrl; var loggerFactory = new LoggerFactory(); - loggerFactory.AddConsole(LogLevel.Debug); - var logger = loggerFactory.CreateLogger(); - logger.LogInformation("Connecting to {0}", baseUrl); + Console.WriteLine("Connecting to {0}", baseUrl); var connection = new HubConnection(new Uri(baseUrl), new JsonNetInvocationAdapter(), loggerFactory); try { await connection.StartAsync(); - logger.LogInformation("Connected to {0}", baseUrl); + Console.WriteLine("Connected to {0}", baseUrl); var cts = new CancellationTokenSource(); Console.CancelKeyPress += (sender, a) => { a.Cancel = true; - logger.LogInformation("Stopping loops..."); + Console.WriteLine("Stopping loops..."); cts.Cancel(); }; @@ -43,21 +51,32 @@ namespace ClientSample connection.On("Send", new[] { typeof(string) }, a => { var message = (string)a[0]; - Console.WriteLine("RECEIVED: " + message); + Console.WriteLine(message); }); while (!cts.Token.IsCancellationRequested) { - var line = Console.ReadLine(); - logger.LogInformation("Sending: {0}", line); + var line = await Task.Run(() => Console.ReadLine(), cts.Token); - await connection.Invoke("Send", line); + if (line == null) + { + break; + } + + await connection.Invoke("Send", cts.Token, line); } } + catch (AggregateException aex) when (aex.InnerExceptions.All(e => e is OperationCanceledException)) + { + } + catch (OperationCanceledException) + { + } finally { await connection.DisposeAsync(); } + return 0; } } } diff --git a/samples/ClientSample/Program.cs b/samples/ClientSample/Program.cs index 951fd17f38..d049ce921a 100644 --- a/samples/ClientSample/Program.cs +++ b/samples/ClientSample/Program.cs @@ -1,11 +1,51 @@ -// Copyright (c) .NET Foundation. All rights reserved. +// Copyright (c) .NET Foundation. All rights reserved. // Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information. +using System; +using System.Diagnostics; +using System.Linq; +using Microsoft.Extensions.CommandLineUtils; + namespace ClientSample { public class Program { - //public static void Main(string[] args) => HubSample.MainAsync(args).Wait(); - public static void Main(string[] args) => RawSample.MainAsync(args).Wait(); + public static void Main(string[] args) + { + if (args.Contains("--debug")) + { + Console.WriteLine($"Ready for debugger to attach. Process ID: {Process.GetCurrentProcess().Id}"); + Console.Write("Press ENTER to Continue"); + Console.ReadLine(); + args = args.Except(new[] { "--debug" }).ToArray(); + } + + var app = new CommandLineApplication(); + app.FullName = "SignalR Client Samples"; + app.Description = "Client Samples for SignalR"; + + RawSample.Register(app); + HubSample.Register(app); + + app.Command("help", cmd => + { + cmd.Description = "Get help for the application, or a specific command"; + + var commandArgument = cmd.Argument("", "The command to get help for"); + cmd.OnExecute(() => + { + app.ShowHelp(commandArgument.Value); + return 0; + }); + }); + + app.OnExecute(() => + { + app.ShowHelp(); + return 0; + }); + + app.Execute(args); + } } } diff --git a/samples/ClientSample/RawSample.cs b/samples/ClientSample/RawSample.cs index 85605ad3aa..b2ebc72da7 100644 --- a/samples/ClientSample/RawSample.cs +++ b/samples/ClientSample/RawSample.cs @@ -10,70 +10,73 @@ using System.Threading; using System.Threading.Tasks; using Microsoft.AspNetCore.Sockets; using Microsoft.AspNetCore.Sockets.Client; +using Microsoft.Extensions.CommandLineUtils; using Microsoft.Extensions.Logging; namespace ClientSample { internal class RawSample { - public static async Task MainAsync(string[] args) + internal static void Register(CommandLineApplication app) { - if (args.Contains("--debug")) + app.Command("raw", cmd => { - Console.WriteLine($"Ready for debugger to attach. Process ID: {Process.GetCurrentProcess().Id}"); - Console.Write("Press ENTER to Continue"); - Console.ReadLine(); - args = args.Except(new[] { "--debug" }).ToArray(); - } + cmd.Description = "Tests a connection to an endpoint"; - var baseUrl = "http://localhost:5000/chat"; - if (args.Length > 0) - { - baseUrl = args[0]; - } + var baseUrlArgument = cmd.Argument("", "The URL to the Chat EndPoint to test"); + + cmd.OnExecute(() => ExecuteAsync(baseUrlArgument.Value)); + }); + } + + public static async Task ExecuteAsync(string baseUrl) + { + baseUrl = string.IsNullOrEmpty(baseUrl) ? "http://localhost:5000/chat" : baseUrl; var loggerFactory = new LoggerFactory(); - loggerFactory.AddConsole(LogLevel.Debug); var logger = loggerFactory.CreateLogger(); - logger.LogInformation("Connecting to {0}", baseUrl); + Console.WriteLine($"Connecting to {baseUrl}..."); var connection = new Connection(new Uri(baseUrl), loggerFactory); try { var cts = new CancellationTokenSource(); - connection.Received += (data, format) => logger.LogInformation($"Received: {Encoding.UTF8.GetString(data)}"); + connection.Received += (data, format) => Console.WriteLine($"{Encoding.UTF8.GetString(data)}"); connection.Closed += e => cts.Cancel(); await connection.StartAsync(); - logger.LogInformation("Connected to {0}", baseUrl); + Console.WriteLine($"Connected to {baseUrl}"); Console.CancelKeyPress += (sender, a) => { a.Cancel = true; - logger.LogInformation("Stopping loops..."); cts.Cancel(); }; - await StartSending(loggerFactory.CreateLogger("SendLoop"), connection, cts.Token).ContinueWith(_ => cts.Cancel()); + while (!cts.Token.IsCancellationRequested) + { + var line = await Task.Run(() => Console.ReadLine(), cts.Token); + + if (line == null) + { + break; + } + + await connection.SendAsync(Encoding.UTF8.GetBytes(line), MessageType.Text, cts.Token); + } + } + catch (AggregateException aex) when (aex.InnerExceptions.All(e => e is OperationCanceledException)) + { + } + catch (OperationCanceledException) + { } finally { await connection.DisposeAsync(); } - } - - private static async Task StartSending(ILogger logger, Connection connection, CancellationToken cancellationToken) - { - logger.LogInformation("Send loop starting"); - while (!cancellationToken.IsCancellationRequested) - { - var line = Console.ReadLine(); - logger.LogInformation("Sending: {0}", line); - - await connection.SendAsync(Encoding.UTF8.GetBytes(line), MessageType.Text); - } - logger.LogInformation("Send loop terminated"); + return 0; } } } diff --git a/samples/SocketsSample/EndPoints/MessagesEndPoint.cs b/samples/SocketsSample/EndPoints/MessagesEndPoint.cs index 643f9a9c4b..5eec621674 100644 --- a/samples/SocketsSample/EndPoints/MessagesEndPoint.cs +++ b/samples/SocketsSample/EndPoints/MessagesEndPoint.cs @@ -27,7 +27,9 @@ namespace SocketsSample.EndPoints if (connection.Transport.Input.TryRead(out message)) { // We can avoid the copy here but we'll deal with that later - await Broadcast(message.Payload, message.Type, message.EndOfMessage); + var text = Encoding.UTF8.GetString(message.Payload); + text = $"{connection.ConnectionId}: {text}"; + await Broadcast(Encoding.UTF8.GetBytes(text), message.Type, message.EndOfMessage); } } } diff --git a/samples/SocketsSample/Program.cs b/samples/SocketsSample/Program.cs index 9d1627b5ea..475d8da752 100644 --- a/samples/SocketsSample/Program.cs +++ b/samples/SocketsSample/Program.cs @@ -1,12 +1,9 @@ -// Copyright (c) .NET Foundation. All rights reserved. +// Copyright (c) .NET Foundation. All rights reserved. // Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information. -using System; -using System.Collections.Generic; using System.IO; -using System.Linq; -using System.Threading.Tasks; using Microsoft.AspNetCore.Hosting; +using Microsoft.Extensions.Configuration; namespace SocketsSample { @@ -14,7 +11,12 @@ namespace SocketsSample { public static void Main(string[] args) { + var config = new ConfigurationBuilder() + .AddCommandLine(args) + .Build(); + var host = new WebHostBuilder() + .UseConfiguration(config) .UseKestrel() .UseContentRoot(Directory.GetCurrentDirectory()) .UseIISIntegration() diff --git a/samples/SocketsSample/SocketsSample.csproj b/samples/SocketsSample/SocketsSample.csproj index 89f8421b81..d63ad18414 100644 --- a/samples/SocketsSample/SocketsSample.csproj +++ b/samples/SocketsSample/SocketsSample.csproj @@ -20,12 +20,12 @@ + - + diff --git a/samples/SocketsSample/Startup.cs b/samples/SocketsSample/Startup.cs index 91065bd568..83da67ea98 100644 --- a/samples/SocketsSample/Startup.cs +++ b/samples/SocketsSample/Startup.cs @@ -1,4 +1,4 @@ -// Copyright (c) .NET Foundation. All rights reserved. +// Copyright (c) .NET Foundation. All rights reserved. // Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information. using Microsoft.AspNetCore.Builder; @@ -38,7 +38,7 @@ namespace SocketsSample // This method gets called by the runtime. Use this method to configure the HTTP request pipeline. public void Configure(IApplicationBuilder app, IHostingEnvironment env, ILoggerFactory loggerFactory) { - loggerFactory.AddConsole(LogLevel.Debug); + loggerFactory.AddConsole(LogLevel.Trace); app.UseFileServer(); diff --git a/src/Microsoft.AspNetCore.Sockets/ConnectionManager.cs b/src/Microsoft.AspNetCore.Sockets/ConnectionManager.cs index 0c811c1894..8148fdebab 100644 --- a/src/Microsoft.AspNetCore.Sockets/ConnectionManager.cs +++ b/src/Microsoft.AspNetCore.Sockets/ConnectionManager.cs @@ -1,4 +1,4 @@ -// Copyright (c) .NET Foundation. All rights reserved. +// Copyright (c) .NET Foundation. All rights reserved. // Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information. using System;