clean up client sample (#392)

This commit is contained in:
Andrew Stanton-Nurse 2017-04-18 12:41:23 -07:00 committed by GitHub
parent e691e1cff8
commit 2d278009b2
9 changed files with 126 additions and 59 deletions

View File

@ -16,6 +16,7 @@
<PackageReference Include="System.Net.WebSockets.Client" Version="$(CoreFxVersion)" /> <PackageReference Include="System.Net.WebSockets.Client" Version="$(CoreFxVersion)" />
<PackageReference Include="Microsoft.Extensions.Logging.Console" Version="$(AspNetCoreVersion)" /> <PackageReference Include="Microsoft.Extensions.Logging.Console" Version="$(AspNetCoreVersion)" />
<PackageReference Include="Microsoft.Extensions.Logging" Version="$(AspNetCoreVersion)" /> <PackageReference Include="Microsoft.Extensions.Logging" Version="$(AspNetCoreVersion)" />
<PackageReference Include="Microsoft.Extensions.CommandLineUtils.Sources" Version="$(AspNetCoreVersion)" PrivateAssets="All" />
</ItemGroup> </ItemGroup>
</Project> </Project>

View File

@ -2,40 +2,48 @@
// Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information. // Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information.
using System; using System;
using System.Linq;
using System.Threading; using System.Threading;
using System.Threading.Tasks; using System.Threading.Tasks;
using Microsoft.AspNetCore.SignalR; using Microsoft.AspNetCore.SignalR;
using Microsoft.AspNetCore.SignalR.Client; using Microsoft.AspNetCore.SignalR.Client;
using Microsoft.Extensions.CommandLineUtils;
using Microsoft.Extensions.Logging; using Microsoft.Extensions.Logging;
namespace ClientSample namespace ClientSample
{ {
internal class HubSample internal class HubSample
{ {
public static async Task MainAsync(string[] args) internal static void Register(CommandLineApplication app)
{ {
var baseUrl = "http://localhost:5000/hubs"; app.Command("hub", cmd =>
if (args.Length > 0)
{ {
baseUrl = args[0]; cmd.Description = "Tests a connection to a hub";
}
var baseUrlArgument = cmd.Argument("<BASEURL>", "The URL to the Chat Hub to test");
cmd.OnExecute(() => ExecuteAsync(baseUrlArgument.Value));
});
}
public static async Task<int> ExecuteAsync(string baseUrl)
{
baseUrl = string.IsNullOrEmpty(baseUrl) ? "http://localhost:5000/hubs" : baseUrl;
var loggerFactory = new LoggerFactory(); var loggerFactory = new LoggerFactory();
loggerFactory.AddConsole(LogLevel.Debug);
var logger = loggerFactory.CreateLogger<Program>();
logger.LogInformation("Connecting to {0}", baseUrl); Console.WriteLine("Connecting to {0}", baseUrl);
var connection = new HubConnection(new Uri(baseUrl), new JsonNetInvocationAdapter(), loggerFactory); var connection = new HubConnection(new Uri(baseUrl), new JsonNetInvocationAdapter(), loggerFactory);
try try
{ {
await connection.StartAsync(); await connection.StartAsync();
logger.LogInformation("Connected to {0}", baseUrl); Console.WriteLine("Connected to {0}", baseUrl);
var cts = new CancellationTokenSource(); var cts = new CancellationTokenSource();
Console.CancelKeyPress += (sender, a) => Console.CancelKeyPress += (sender, a) =>
{ {
a.Cancel = true; a.Cancel = true;
logger.LogInformation("Stopping loops..."); Console.WriteLine("Stopping loops...");
cts.Cancel(); cts.Cancel();
}; };
@ -43,21 +51,32 @@ namespace ClientSample
connection.On("Send", new[] { typeof(string) }, a => connection.On("Send", new[] { typeof(string) }, a =>
{ {
var message = (string)a[0]; var message = (string)a[0];
Console.WriteLine("RECEIVED: " + message); Console.WriteLine(message);
}); });
while (!cts.Token.IsCancellationRequested) while (!cts.Token.IsCancellationRequested)
{ {
var line = Console.ReadLine(); var line = await Task.Run(() => Console.ReadLine(), cts.Token);
logger.LogInformation("Sending: {0}", line);
await connection.Invoke<object>("Send", line); if (line == null)
{
break;
}
await connection.Invoke<object>("Send", cts.Token, line);
} }
} }
catch (AggregateException aex) when (aex.InnerExceptions.All(e => e is OperationCanceledException))
{
}
catch (OperationCanceledException)
{
}
finally finally
{ {
await connection.DisposeAsync(); await connection.DisposeAsync();
} }
return 0;
} }
} }
} }

View File

@ -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. // 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 namespace ClientSample
{ {
public class Program public class Program
{ {
//public static void Main(string[] args) => HubSample.MainAsync(args).Wait(); public static void Main(string[] args)
public static void Main(string[] args) => RawSample.MainAsync(args).Wait(); {
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("<COMMAND>", "The command to get help for");
cmd.OnExecute(() =>
{
app.ShowHelp(commandArgument.Value);
return 0;
});
});
app.OnExecute(() =>
{
app.ShowHelp();
return 0;
});
app.Execute(args);
}
} }
} }

View File

@ -10,70 +10,73 @@ using System.Threading;
using System.Threading.Tasks; using System.Threading.Tasks;
using Microsoft.AspNetCore.Sockets; using Microsoft.AspNetCore.Sockets;
using Microsoft.AspNetCore.Sockets.Client; using Microsoft.AspNetCore.Sockets.Client;
using Microsoft.Extensions.CommandLineUtils;
using Microsoft.Extensions.Logging; using Microsoft.Extensions.Logging;
namespace ClientSample namespace ClientSample
{ {
internal class RawSample 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}"); cmd.Description = "Tests a connection to an endpoint";
Console.Write("Press ENTER to Continue");
Console.ReadLine();
args = args.Except(new[] { "--debug" }).ToArray();
}
var baseUrl = "http://localhost:5000/chat"; var baseUrlArgument = cmd.Argument("<BASEURL>", "The URL to the Chat EndPoint to test");
if (args.Length > 0)
{ cmd.OnExecute(() => ExecuteAsync(baseUrlArgument.Value));
baseUrl = args[0]; });
} }
public static async Task<int> ExecuteAsync(string baseUrl)
{
baseUrl = string.IsNullOrEmpty(baseUrl) ? "http://localhost:5000/chat" : baseUrl;
var loggerFactory = new LoggerFactory(); var loggerFactory = new LoggerFactory();
loggerFactory.AddConsole(LogLevel.Debug);
var logger = loggerFactory.CreateLogger<Program>(); var logger = loggerFactory.CreateLogger<Program>();
logger.LogInformation("Connecting to {0}", baseUrl); Console.WriteLine($"Connecting to {baseUrl}...");
var connection = new Connection(new Uri(baseUrl), loggerFactory); var connection = new Connection(new Uri(baseUrl), loggerFactory);
try try
{ {
var cts = new CancellationTokenSource(); 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(); connection.Closed += e => cts.Cancel();
await connection.StartAsync(); await connection.StartAsync();
logger.LogInformation("Connected to {0}", baseUrl); Console.WriteLine($"Connected to {baseUrl}");
Console.CancelKeyPress += (sender, a) => Console.CancelKeyPress += (sender, a) =>
{ {
a.Cancel = true; a.Cancel = true;
logger.LogInformation("Stopping loops...");
cts.Cancel(); 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 finally
{ {
await connection.DisposeAsync(); await connection.DisposeAsync();
} }
} return 0;
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");
} }
} }
} }

View File

@ -27,7 +27,9 @@ namespace SocketsSample.EndPoints
if (connection.Transport.Input.TryRead(out message)) if (connection.Transport.Input.TryRead(out message))
{ {
// We can avoid the copy here but we'll deal with that later // 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);
} }
} }
} }

View File

@ -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. // 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.IO;
using System.Linq;
using System.Threading.Tasks;
using Microsoft.AspNetCore.Hosting; using Microsoft.AspNetCore.Hosting;
using Microsoft.Extensions.Configuration;
namespace SocketsSample namespace SocketsSample
{ {
@ -14,7 +11,12 @@ namespace SocketsSample
{ {
public static void Main(string[] args) public static void Main(string[] args)
{ {
var config = new ConfigurationBuilder()
.AddCommandLine(args)
.Build();
var host = new WebHostBuilder() var host = new WebHostBuilder()
.UseConfiguration(config)
.UseKestrel() .UseKestrel()
.UseContentRoot(Directory.GetCurrentDirectory()) .UseContentRoot(Directory.GetCurrentDirectory())
.UseIISIntegration() .UseIISIntegration()

View File

@ -20,12 +20,12 @@
<PackageReference Include="Microsoft.AspNetCore.Server.Kestrel" Version="$(AspNetCoreVersion)" /> <PackageReference Include="Microsoft.AspNetCore.Server.Kestrel" Version="$(AspNetCoreVersion)" />
<PackageReference Include="Microsoft.AspNetCore.StaticFiles" Version="$(AspNetCoreVersion)" /> <PackageReference Include="Microsoft.AspNetCore.StaticFiles" Version="$(AspNetCoreVersion)" />
<PackageReference Include="Microsoft.Extensions.Logging.Console" Version="$(AspNetCoreVersion)" /> <PackageReference Include="Microsoft.Extensions.Logging.Console" Version="$(AspNetCoreVersion)" />
<PackageReference Include="Microsoft.Extensions.Configuration.CommandLine" Version="$(AspNetCoreVersion)" />
<PackageReference Include="Google.Protobuf" Version="$(GoogleProtobufVersion)" /> <PackageReference Include="Google.Protobuf" Version="$(GoogleProtobufVersion)" />
</ItemGroup> </ItemGroup>
<Target Name="CopyTSClient" BeforeTargets="AfterBuild"> <Target Name="CopyTSClient" BeforeTargets="AfterBuild">
<Copy SourceFiles="$(MSBuildThisFileDirectory)..\..\client-ts\dist\browser\signalr-client.js" <Copy SourceFiles="$(MSBuildThisFileDirectory)..\..\client-ts\dist\browser\signalr-client.js" DestinationFolder="$(MSBuildThisFileDirectory)wwwroot\lib\signalr-client" />
DestinationFolder="$(MSBuildThisFileDirectory)wwwroot\lib\signalr-client" />
</Target> </Target>
</Project> </Project>

View File

@ -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. // Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information.
using Microsoft.AspNetCore.Builder; 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. // 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) public void Configure(IApplicationBuilder app, IHostingEnvironment env, ILoggerFactory loggerFactory)
{ {
loggerFactory.AddConsole(LogLevel.Debug); loggerFactory.AddConsole(LogLevel.Trace);
app.UseFileServer(); app.UseFileServer();

View File

@ -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. // Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information.
using System; using System;