Skip to content

Commit

Permalink
networking dotnet7 #146 #149
Browse files Browse the repository at this point in the history
  • Loading branch information
christiannagel committed Nov 15, 2022
1 parent b7dfb36 commit 95ce5e0
Show file tree
Hide file tree
Showing 15 changed files with 71 additions and 70 deletions.
2 changes: 1 addition & 1 deletion 2_Libs/Networking/DnsLookup/DnsLookup.csproj
Original file line number Diff line number Diff line change
@@ -1,7 +1,7 @@
<Project Sdk="Microsoft.NET.Sdk">

<PropertyGroup>
<TargetFramework>net6.0</TargetFramework>
<TargetFramework>net7.0</TargetFramework>
<OutputType>Exe</OutputType>
<Nullable>enable</Nullable>
<ImplicitUsings>enable</ImplicitUsings>
Expand Down
2 changes: 1 addition & 1 deletion 2_Libs/Networking/HttpClientSample/FaultHandlingSample.cs
Original file line number Diff line number Diff line change
Expand Up @@ -28,7 +28,7 @@ public async Task RunAsync()
}
catch (HttpRequestException ex)
{
_logger.LogError(ex, ex.Message);
_logger.LogError(ex, "Error: {error}", ex.Message);
}
}
}
10 changes: 5 additions & 5 deletions 2_Libs/Networking/HttpClientSample/HttpClientSample.csproj
Original file line number Diff line number Diff line change
@@ -1,17 +1,17 @@
<Project Sdk="Microsoft.NET.Sdk">

<PropertyGroup>
<TargetFramework>net6.0</TargetFramework>
<TargetFramework>net7.0</TargetFramework>
<OutputType>Exe</OutputType>
<Nullable>enable</Nullable>
<ImplicitUsings>enable</ImplicitUsings>
</PropertyGroup>

<ItemGroup>
<PackageReference Include="Microsoft.Extensions.Hosting" Version="6.0.1" />
<PackageReference Include="Microsoft.Extensions.Http" Version="6.0.0" />
<PackageReference Include="Microsoft.Extensions.Http.Polly" Version="6.0.10" />
<PackageReference Include="System.CommandLine.Hosting" Version="0.4.0-alpha.21617.1" />
<PackageReference Include="Microsoft.Extensions.Hosting" Version="7.0.0" />
<PackageReference Include="Microsoft.Extensions.Http" Version="7.0.0" />
<PackageReference Include="Microsoft.Extensions.Http.Polly" Version="7.0.0" />
<PackageReference Include="System.CommandLine.Hosting" Version="0.4.0-alpha.22272.1" />
</ItemGroup>

<ItemGroup>
Expand Down
44 changes: 20 additions & 24 deletions 2_Libs/Networking/HttpClientSample/Program.cs
Original file line number Diff line number Diff line change
Expand Up @@ -5,49 +5,45 @@

using System.CommandLine;
using System.CommandLine.Builder;
using System.CommandLine.Hosting;
using System.CommandLine.Invocation;
using System.CommandLine.Parsing;

await BuildCommandLine()
.UseHost(_ => GetHostBuilder())
.UseDefaults()
.Build()
.InvokeAsync(args);

IHostBuilder GetHostBuilder() =>
Host.CreateDefaultBuilder()
using var host = Host.CreateDefaultBuilder()
.ConfigureServices((context, services) =>
{
var httpClientSettings = context.Configuration.GetSection("HttpClient");
services.Configure<HttpClientSamplesOptions>(httpClientSettings);
services.AddHttpClient<HttpClientSamples>(httpClient =>
{
httpClient.BaseAddress = new Uri(httpClientSettings["Url"]);
httpClient.BaseAddress = new Uri(httpClientSettings["Url"] ?? throw new InvalidOperationException("Url not configured"));
});
services.Configure<LimitCallsHandlerOptions>(context.Configuration.GetSection("RateLimit"));
services.AddTransient<LimitCallsHandler>();
services.AddHttpClient<HttpClientSampleWithMessageHandler>(httpClient =>
{
httpClient.BaseAddress = new Uri(httpClientSettings["Url"]);
httpClient.BaseAddress = new Uri(httpClientSettings["Url"] ?? throw new InvalidOperationException("Url not configured"));
}).AddHttpMessageHandler<LimitCallsHandler>().SetHandlerLifetime(Timeout.InfiniteTimeSpan);
services.AddHttpClient("racersClient")
.ConfigureHttpClient(httpClient =>
{
httpClient.BaseAddress = new Uri(httpClientSettings["Url"]);
httpClient.BaseAddress = new Uri(httpClientSettings["Url"] ?? throw new InvalidOperationException("Url not configured"));
});
services.AddTransient<NamedClientSample>();
services.AddHttpClient<FaultHandlingSample>(httpClient =>
{
httpClient.BaseAddress = new Uri(httpClientSettings["InvalidUrl"]);
})
httpClient.BaseAddress = new Uri(httpClientSettings["InvalidUrl"] ?? throw new InvalidOperationException("Url not configured"));
})
//.AddPolicyHandler(GetRetryPolicy())
.AddTransientHttpErrorPolicy(
policy => policy.WaitAndRetryAsync(new[] { TimeSpan.FromSeconds(1), TimeSpan.FromSeconds(3), TimeSpan.FromSeconds(5) }));
});
}).Build();

await BuildCommandLine()
.UseDefaults()
.Build()
.InvokeAsync(args);

//IAsyncPolicy<HttpResponseMessage> GetRetryPolicy()
// => HttpPolicyExtensions
Expand All @@ -59,47 +55,47 @@ CommandLineBuilder BuildCommandLine()
{
RootCommand rootCommand = new("HttpClientSample");
Command simpleCommand = new("simple");
simpleCommand.SetHandler<IHost>(async host =>
simpleCommand.SetHandler(async () =>
{
var service = host.Services.GetRequiredService<HttpClientSamples>();
await service.SimpleGetRequestAsync();
});
rootCommand.AddCommand(simpleCommand);

Command httpRequestMessageCommand = new("httprequest");
httpRequestMessageCommand.SetHandler<IHost>(async host =>
httpRequestMessageCommand.SetHandler(async () =>
{
var service = host.Services.GetRequiredService<HttpClientSamples>();
await service.UseHttpRequestMessageAsync();
});
rootCommand.AddCommand(httpRequestMessageCommand);

Command exceptionCommand = new("exception");
exceptionCommand.SetHandler<IHost>(async host =>
exceptionCommand.SetHandler(async () =>
{
var service = host.Services.GetRequiredService<HttpClientSamples>();
await service.ThrowExceptionAsync();
});
rootCommand.AddCommand(exceptionCommand);

Command headerCommand = new("headers");
headerCommand.SetHandler<IHost>(async host =>
headerCommand.SetHandler(async () =>
{
var service = host.Services.GetRequiredService<HttpClientSamples>();
await service.AddHttpHeadersAsync();
});
rootCommand.AddCommand(headerCommand);

Command http2Command = new("http2");
http2Command.SetHandler<IHost>(async host =>
http2Command.SetHandler(async () =>
{
var service = host.Services.GetRequiredService<HttpClientSamples>();
await service.UseHttp2();
});
rootCommand.AddCommand(http2Command);

Command messageHandlerCommand = new("messagehandler");
messageHandlerCommand.SetHandler<IHost>(async host =>
messageHandlerCommand.SetHandler(async () =>
{
var service = host.Services.GetRequiredService<HttpClientSampleWithMessageHandler>();
for (int i = 0; i < 10; i++)
Expand All @@ -110,15 +106,15 @@ CommandLineBuilder BuildCommandLine()
rootCommand.AddCommand(messageHandlerCommand);

Command namedClientCommand = new("named");
namedClientCommand.SetHandler<IHost>(async host =>
namedClientCommand.SetHandler(async () =>
{
var service = host.Services.GetRequiredService<NamedClientSample>();
await service.RunAsync();
});
rootCommand.AddCommand(namedClientCommand);

Command pollyCommand = new("retry");
pollyCommand.SetHandler<IHost>(async host =>
pollyCommand.SetHandler(async () =>
{
var service = host.Services.GetRequiredService<FaultHandlingSample>();
await service.RunAsync();
Expand Down
24 changes: 15 additions & 9 deletions 2_Libs/Networking/HttpServerSample/GenerateHtml.cs
Original file line number Diff line number Diff line change
Expand Up @@ -7,19 +7,25 @@ public class GenerateHtml
private readonly ILogger _logger;
public GenerateHtml(ILogger<GenerateHtml> logger) => _logger = logger;

private static string s_htmlFormat =
"<!DOCTYPE html>\r\n<html><head><title>{0}</title></head>" +
"<body>{1}</body></html>";
private static readonly string s_htmlFormat = """
<!DOCTYPE html>
<html>
<head>
<title>{0}</title></head>
<body>{1}</body></html>
""";

public string GetHtmlContent(HttpRequest request)
{
string title = "Sample Listener using Kestrel";

string content = $"<h1>Hello from the server</h1>" +
$"<h2>Header Info</h2>" +
$"{string.Join(' ', GetHeaderInfo(request.Headers))}" +
$"<h2>Request Object Information</h2>" +
$"{string.Join(' ', GetRequestInfo(request))}";
string content = $$"""
<h1>Hello from the server</h1>
<h2>Header Info</h2>
{{string.Join(' ', GetHeaderInfo(request.Headers))}}
<h2>Request Object Information</h2>
{{string.Join(' ', GetRequestInfo(request))}}
""";

return string.Format(s_htmlFormat, title, content);
}
Expand Down Expand Up @@ -50,7 +56,7 @@ private IEnumerable<string> GetRequestInfo(HttpRequest request)

private IEnumerable<string> GetHeaderInfo(IHeaderDictionary headers)
{
List<(string Key, string Value)> values = new();
List<(string Key, string? Value)> values = new();
var keys = headers.Keys;
foreach (var key in keys)
{
Expand Down
2 changes: 1 addition & 1 deletion 2_Libs/Networking/HttpServerSample/HttpServerSample.csproj
Original file line number Diff line number Diff line change
@@ -1,7 +1,7 @@
<Project Sdk="Microsoft.NET.Sdk.Web">

<PropertyGroup>
<TargetFramework>net6.0</TargetFramework>
<TargetFramework>net7.0</TargetFramework>
<Nullable>enable</Nullable>
<ImplicitUsings>enable</ImplicitUsings>
</PropertyGroup>
Expand Down
6 changes: 3 additions & 3 deletions 2_Libs/Networking/SocketClient/SocketClient.csproj
Original file line number Diff line number Diff line change
@@ -1,15 +1,15 @@
<Project Sdk="Microsoft.NET.Sdk">

<PropertyGroup>
<TargetFramework>net6.0</TargetFramework>
<TargetFramework>net7.0</TargetFramework>
<OutputType>Exe</OutputType>
<Nullable>enable</Nullable>
<ImplicitUsings>enable</ImplicitUsings>
</PropertyGroup>

<ItemGroup>
<PackageReference Include="Microsoft.Extensions.Hosting" Version="6.0.1" />
<PackageReference Include="System.IO.Pipelines" Version="6.0.3" />
<PackageReference Include="Microsoft.Extensions.Hosting" Version="7.0.0" />
<PackageReference Include="System.IO.Pipelines" Version="7.0.0" />
</ItemGroup>

<ItemGroup>
Expand Down
24 changes: 12 additions & 12 deletions 2_Libs/Networking/SocketServer/EchoServer.cs
Original file line number Diff line number Diff line change
Expand Up @@ -35,33 +35,33 @@ public async Task StartListenerAsync(CancellationToken cancellationToken = defau

listener.Bind(new IPEndPoint(IPAddress.Any, _port));
listener.Listen(backlog: 15);
_logger.LogTrace("EchoListener started on port {0}", _port);
_logger.LogTrace("EchoListener started on port {port}", _port);
while (true)
{
if (cancellationToken.IsCancellationRequested)
{
cancellationToken.ThrowIfCancellationRequested();
break;
}
var socket = await listener.AcceptAsync();
var socket = await listener.AcceptAsync(cancellationToken);
if (!socket.Connected)
{
_logger.LogWarning("Client not connected after accept");
break;
}

_logger.LogInformation("client connected, local {0}, remote {1}", socket.LocalEndPoint, socket.RemoteEndPoint);
_logger.LogInformation("client connected, local {localendpoint}, remote {remoteendpoint}", socket.LocalEndPoint, socket.RemoteEndPoint);

Task _ = ProcessClientJobAsync(socket);
Task _ = ProcessClientJobAsync(socket, cancellationToken);
}
}
catch (SocketException ex)
{
_logger.LogError(ex, ex.Message);
_logger.LogError(ex, "Error {error}", ex.Message);
}
catch (Exception ex)
{
_logger.LogError(ex, ex.Message);
_logger.LogError(ex, "Error {error}", ex.Message);
throw;
}
}
Expand Down Expand Up @@ -89,7 +89,7 @@ private async Task ProcessClientJobAsync(Socket socket, CancellationToken cancel
if (buffer.IsSingleSegment)
{
string data = Encoding.UTF8.GetString(buffer.FirstSpan);
_logger.LogTrace("received data {0} from the client {1}", data, socket.RemoteEndPoint);
_logger.LogTrace("received data {data} from the client {endpoint}", data, socket.RemoteEndPoint);

// send the data back
await writer.WriteAsync(buffer.First, cancellationToken);
Expand All @@ -101,7 +101,7 @@ private async Task ProcessClientJobAsync(Socket socket, CancellationToken cancel
{
segmentNumber++;
string data = Encoding.UTF8.GetString(item.Span);
_logger.LogTrace("received data {0} from the client {1} in the {2}. segment", data, socket.RemoteEndPoint, segmentNumber);
_logger.LogTrace("received data {data} from the client {endpoint} in the {segment}. segment", data, socket.RemoteEndPoint, segmentNumber);

// send the data back
await writer.WriteAsync(item, cancellationToken);
Expand All @@ -114,17 +114,17 @@ private async Task ProcessClientJobAsync(Socket socket, CancellationToken cancel
}
catch (SocketException ex)
{
_logger.LogError(ex, ex.Message);
_logger.LogError(ex, "{error}", ex.Message);
}
catch (IOException ex) when ((ex.InnerException is SocketException socketException) && (socketException.ErrorCode is 10054))
{
_logger.LogInformation("client {0} closed the connection", socket.RemoteEndPoint);
_logger.LogInformation("client {endpoint} closed the connection", socket.RemoteEndPoint);
}
catch (Exception ex)
{
_logger.LogError(ex, "ex.Message with client {0}", socket.RemoteEndPoint);
_logger.LogError(ex, "ex.Message with client {endpoint}", socket.RemoteEndPoint);
throw;
}
_logger.LogTrace("Closed stream and client socket {0}", socket.RemoteEndPoint);
_logger.LogTrace("Closed stream and client socket {endpoint}", socket.RemoteEndPoint);
}
}
6 changes: 3 additions & 3 deletions 2_Libs/Networking/SocketServer/SocketServer.csproj
Original file line number Diff line number Diff line change
@@ -1,15 +1,15 @@
<Project Sdk="Microsoft.NET.Sdk">

<PropertyGroup>
<TargetFramework>net6.0</TargetFramework>
<TargetFramework>net7.0</TargetFramework>
<OutputType>Exe</OutputType>
<Nullable>enable</Nullable>
<ImplicitUsings>enable</ImplicitUsings>
</PropertyGroup>

<ItemGroup>
<PackageReference Include="Microsoft.Extensions.Hosting" Version="6.0.1" />
<PackageReference Include="System.IO.Pipelines" Version="6.0.3" />
<PackageReference Include="Microsoft.Extensions.Hosting" Version="7.0.0" />
<PackageReference Include="System.IO.Pipelines" Version="7.0.0" />
</ItemGroup>

<ItemGroup>
Expand Down
4 changes: 2 additions & 2 deletions 2_Libs/Networking/TcpClientSample/TcpClientSample.csproj
Original file line number Diff line number Diff line change
@@ -1,14 +1,14 @@
<Project Sdk="Microsoft.NET.Sdk">

<PropertyGroup>
<TargetFramework>net6.0</TargetFramework>
<TargetFramework>net7.0</TargetFramework>
<OutputType>Exe</OutputType>
<Nullable>enable</Nullable>
<ImplicitUsings>enable</ImplicitUsings>
</PropertyGroup>

<ItemGroup>
<PackageReference Include="Microsoft.Extensions.Hosting" Version="6.0.1" />
<PackageReference Include="Microsoft.Extensions.Hosting" Version="7.0.0" />
</ItemGroup>

<ItemGroup>
Expand Down
4 changes: 2 additions & 2 deletions 2_Libs/Networking/TcpServer/TcpServer.csproj
Original file line number Diff line number Diff line change
@@ -1,14 +1,14 @@
<Project Sdk="Microsoft.NET.Sdk">

<PropertyGroup>
<TargetFramework>net6.0</TargetFramework>
<TargetFramework>net7.0</TargetFramework>
<OutputType>Exe</OutputType>
<Nullable>enable</Nullable>
<ImplicitUsings>enable</ImplicitUsings>
</PropertyGroup>

<ItemGroup>
<PackageReference Include="Microsoft.Extensions.Hosting" Version="6.0.1" />
<PackageReference Include="Microsoft.Extensions.Hosting" Version="7.0.0" />
</ItemGroup>

<ItemGroup>
Expand Down
4 changes: 2 additions & 2 deletions 2_Libs/Networking/UdpReceiver/UdpReceiver.csproj
Original file line number Diff line number Diff line change
@@ -1,14 +1,14 @@
<Project Sdk="Microsoft.NET.Sdk">

<PropertyGroup>
<TargetFramework>net6.0</TargetFramework>
<TargetFramework>net7.0</TargetFramework>
<OutputType>Exe</OutputType>
<Nullable>enable</Nullable>
<ImplicitUsings>enable</ImplicitUsings>
</PropertyGroup>

<ItemGroup>
<PackageReference Include="Microsoft.Extensions.Hosting" Version="6.0.1" />
<PackageReference Include="Microsoft.Extensions.Hosting" Version="7.0.0" />
</ItemGroup>

<ItemGroup>
Expand Down
Loading

0 comments on commit 95ce5e0

Please sign in to comment.