Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Add downloader example #1695

Merged
merged 1 commit into from
Apr 18, 2022
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
16 changes: 16 additions & 0 deletions examples/Downloader/Client/Client.csproj
Original file line number Diff line number Diff line change
@@ -0,0 +1,16 @@
<Project Sdk="Microsoft.NET.Sdk">

<PropertyGroup>
<OutputType>Exe</OutputType>
<TargetFramework>net6.0</TargetFramework>
</PropertyGroup>

<ItemGroup>
<Protobuf Include="..\Proto\download.proto" GrpcServices="Client" Link="Protos\download.proto" />

<PackageReference Include="Google.Protobuf" Version="$(GoogleProtobufPackageVersion)" />
<PackageReference Include="Grpc.Net.Client" Version="$(GrpcDotNetPackageVersion)" />
<PackageReference Include="Grpc.Tools" Version="$(GrpcPackageVersion)" PrivateAssets="All" />
</ItemGroup>

</Project>
69 changes: 69 additions & 0 deletions examples/Downloader/Client/Program.cs
Original file line number Diff line number Diff line change
@@ -0,0 +1,69 @@
#region Copyright notice and license

// Copyright 2019 The gRPC Authors
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.

#endregion

using Download;
using Grpc.Core;
using Grpc.Net.Client;

namespace Client
{
public class Program
{
static async Task Main(string[] args)
{
using var channel = GrpcChannel.ForAddress("https://localhost:5001");

var client = new Downloader.DownloaderClient(channel);

var downloadsPath = Path.Combine(Environment.CurrentDirectory, "downloads");
var downloadId = Path.GetRandomFileName();
var downloadIdPath = Path.Combine(downloadsPath, downloadId);
Directory.CreateDirectory(downloadIdPath);

Console.WriteLine("Starting call");

using var call = client.DownloadFile(new DownloadFileRequest
{
Id = downloadId
});

await using var writeStream = File.Create(Path.Combine(downloadIdPath, "data.bin"));

await foreach (var message in call.ResponseStream.ReadAllAsync())
{
if (message.Metadata != null)
{
Console.WriteLine("Saving metadata to file");
var metadata = message.Metadata.ToString();
await File.WriteAllTextAsync(Path.Combine(downloadIdPath, "metadata.json"), metadata);
}
if (message.Data != null)
{
var bytes = message.Data.Memory;
Console.WriteLine($"Saving {bytes.Length} bytes to file");
await writeStream.WriteAsync(bytes);
}
}

Console.WriteLine();
Console.WriteLine("Files were saved in: " + downloadIdPath);
Console.WriteLine("Press any key to exit...");
Console.ReadKey();
}
}
}
31 changes: 31 additions & 0 deletions examples/Downloader/Downloader.sln
Original file line number Diff line number Diff line change
@@ -0,0 +1,31 @@

Microsoft Visual Studio Solution File, Format Version 12.00
# Visual Studio Version 17
VisualStudioVersion = 17.1.32328.378
MinimumVisualStudioVersion = 10.0.40219.1
Project("{9A19103F-16F7-4668-BE54-9A1E7A4F7556}") = "Server", "Server\Server.csproj", "{249DA884-CC8F-483C-B1B9-222AB767E722}"
EndProject
Project("{9A19103F-16F7-4668-BE54-9A1E7A4F7556}") = "Client", "Client\Client.csproj", "{7580D422-98F0-441D-B618-DC16A4E2C138}"
EndProject
Global
GlobalSection(SolutionConfigurationPlatforms) = preSolution
Debug|Any CPU = Debug|Any CPU
Release|Any CPU = Release|Any CPU
EndGlobalSection
GlobalSection(ProjectConfigurationPlatforms) = postSolution
{249DA884-CC8F-483C-B1B9-222AB767E722}.Debug|Any CPU.ActiveCfg = Debug|Any CPU
{249DA884-CC8F-483C-B1B9-222AB767E722}.Debug|Any CPU.Build.0 = Debug|Any CPU
{249DA884-CC8F-483C-B1B9-222AB767E722}.Release|Any CPU.ActiveCfg = Release|Any CPU
{249DA884-CC8F-483C-B1B9-222AB767E722}.Release|Any CPU.Build.0 = Release|Any CPU
{7580D422-98F0-441D-B618-DC16A4E2C138}.Debug|Any CPU.ActiveCfg = Debug|Any CPU
{7580D422-98F0-441D-B618-DC16A4E2C138}.Debug|Any CPU.Build.0 = Debug|Any CPU
{7580D422-98F0-441D-B618-DC16A4E2C138}.Release|Any CPU.ActiveCfg = Release|Any CPU
{7580D422-98F0-441D-B618-DC16A4E2C138}.Release|Any CPU.Build.0 = Release|Any CPU
EndGlobalSection
GlobalSection(SolutionProperties) = preSolution
HideSolutionNode = FALSE
EndGlobalSection
GlobalSection(ExtensibilityGlobals) = postSolution
SolutionGuid = {D19E5F88-1F30-4E05-9551-FEFDB3B154EC}
EndGlobalSection
EndGlobal
35 changes: 35 additions & 0 deletions examples/Downloader/Proto/download.proto
Original file line number Diff line number Diff line change
@@ -0,0 +1,35 @@
// Copyright 2019 The gRPC Authors
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.

syntax = "proto3";

package download;

service Downloader {
rpc DownloadFile (DownloadFileRequest) returns (stream DownloadFileResponse);
}

message DownloadFileRequest {
string id = 1;
}

message DownloadFileResponse {
FileMetadata metadata = 1;
bytes data = 2;
}

message FileMetadata {
string file_name = 1;
}

36 changes: 36 additions & 0 deletions examples/Downloader/Server/Program.cs
Original file line number Diff line number Diff line change
@@ -0,0 +1,36 @@
#region Copyright notice and license

// Copyright 2019 The gRPC Authors
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.

#endregion

namespace Server
{
public class Program
{
public static void Main(string[] args)
{
CreateHostBuilder(args).Build().Run();
}

public static IHostBuilder CreateHostBuilder(string[] args) =>
Host.CreateDefaultBuilder(args)
.ConfigureWebHostDefaults(webBuilder =>
{
webBuilder.UseStartup<Startup>();
});
}

}
13 changes: 13 additions & 0 deletions examples/Downloader/Server/Server.csproj
Original file line number Diff line number Diff line change
@@ -0,0 +1,13 @@
<Project Sdk="Microsoft.NET.Sdk.Web">

<PropertyGroup>
<TargetFramework>net6.0</TargetFramework>
</PropertyGroup>

<ItemGroup>
<PackageReference Include="Grpc.AspNetCore" Version="$(GrpcDotNetPackageVersion)" />

<Protobuf Include="..\Proto\download.proto" GrpcServices="Server" Link="Protos\download.proto" />
</ItemGroup>

</Project>
68 changes: 68 additions & 0 deletions examples/Downloader/Server/Services/DownloaderService.cs
Original file line number Diff line number Diff line change
@@ -0,0 +1,68 @@
#region Copyright notice and license

// Copyright 2019 The gRPC Authors
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.

#endregion

using Grpc.Core;
using Download;
using Google.Protobuf;

namespace Server
{
public class DownloaderService : Downloader.DownloaderBase
{
private readonly ILogger _logger;
private const int ChunkSize = 1024 * 32;

public DownloaderService(ILoggerFactory loggerFactory)
{
_logger = loggerFactory.CreateLogger<DownloaderService>();
}

public override async Task DownloadFile(DownloadFileRequest request, IServerStreamWriter<DownloadFileResponse> responseStream, ServerCallContext context)
{
var requestParam = request.Id;
var filename = requestParam switch
{
"4" => "pancakes4.png",
_ => "pancakes.jpg",
};

await responseStream.WriteAsync(new DownloadFileResponse
{
Metadata = new FileMetadata { FileName = filename }
});

var buffer = new byte[ChunkSize];
await using var fileStream = File.OpenRead(filename);

while (true)
{
var numBytesRead = await fileStream.ReadAsync(buffer);
if (numBytesRead == 0)
{
break;
}

_logger.LogInformation("Sending data chunk of {numBytesRead} bytes", numBytesRead);
await responseStream.WriteAsync(new DownloadFileResponse
{
Data = UnsafeByteOperations.UnsafeWrap(buffer.AsMemory(0, numBytesRead))
}) ;
}
}
}
}
43 changes: 43 additions & 0 deletions examples/Downloader/Server/Startup.cs
Original file line number Diff line number Diff line change
@@ -0,0 +1,43 @@
#region Copyright notice and license

// Copyright 2019 The gRPC Authors
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.

#endregion

namespace Server
{
public class Startup
{
public void ConfigureServices(IServiceCollection services)
{
services.AddGrpc();
}

public void Configure(IApplicationBuilder app, IWebHostEnvironment env)
{
if (env.IsDevelopment())
{
app.UseDeveloperExceptionPage();
}

app.UseRouting();

app.UseEndpoints(endpoints =>
{
endpoints.MapGrpcService<DownloaderService>();
});
}
}
}
10 changes: 10 additions & 0 deletions examples/Downloader/Server/appsettings.Development.json
Original file line number Diff line number Diff line change
@@ -0,0 +1,10 @@
{
"Logging": {
"LogLevel": {
"Default": "Debug",
"System": "Information",
"Grpc": "Information",
"Microsoft": "Information"
}
}
}
13 changes: 13 additions & 0 deletions examples/Downloader/Server/appsettings.json
Original file line number Diff line number Diff line change
@@ -0,0 +1,13 @@
{
"Logging": {
"LogLevel": {
"Default": "Information"
}
},
"AllowedHosts": "*",
"Kestrel": {
"EndpointDefaults": {
"Protocols": "Http2"
}
}
}
Binary file added examples/Downloader/Server/pancakes.jpg
Loading
Sorry, something went wrong. Reload?
Sorry, we cannot display this file.
Sorry, this file is invalid so it cannot be displayed.
Binary file added examples/Downloader/Server/pancakes4.png
Loading
Sorry, something went wrong. Reload?
Sorry, we cannot display this file.
Sorry, this file is invalid so it cannot be displayed.
9 changes: 9 additions & 0 deletions examples/README.md
Original file line number Diff line number Diff line change
Expand Up @@ -289,3 +289,12 @@ The uploader shows how to upload a file in chunks using a client streaming gRPC

* Client streaming call
* Binary payload

## [Downloader](./Downloader)

The downloader shows how to download a file in chunks using a server streaming gRPC method.

##### Scenarios:

* Server streaming
* Binary payload