50 lines
1.4 KiB
C#
50 lines
1.4 KiB
C#
using Google.Protobuf;
|
|
using Grpc.Core;
|
|
using TestGrpc;
|
|
|
|
namespace TestGrpc.Services;
|
|
|
|
public class GreeterService : Greeter.GreeterBase
|
|
{
|
|
private readonly ILogger<GreeterService> _logger;
|
|
public GreeterService(ILogger<GreeterService> logger)
|
|
{
|
|
_logger = logger;
|
|
}
|
|
|
|
public override async Task DownloadFile(FileRequest request, IServerStreamWriter<ChunkMsg> responseStream, ServerCallContext context)
|
|
{
|
|
string filePath = request.FilePath;
|
|
|
|
if (!File.Exists(filePath))
|
|
{
|
|
return;
|
|
}
|
|
|
|
var fileInfo = new FileInfo(filePath);
|
|
|
|
var chunk = new ChunkMsg
|
|
{
|
|
FileName = Path.GetFileName(filePath),
|
|
FileSize = fileInfo.Length
|
|
};
|
|
|
|
int fileChunkSize = 64 * 1024;
|
|
|
|
byte[] fileByteArray = File.ReadAllBytes(filePath);
|
|
byte[] fileChunk = new byte[fileChunkSize];
|
|
int fileOffset = 0;
|
|
|
|
while (fileOffset < fileByteArray.Length && !context.CancellationToken.IsCancellationRequested)
|
|
{
|
|
int length = Math.Min(fileChunkSize, fileByteArray.Length - fileOffset);
|
|
Buffer.BlockCopy(fileByteArray, fileOffset, fileChunk, 0, length);
|
|
fileOffset += length;
|
|
ByteString byteString = ByteString.CopyFrom(fileChunk);
|
|
|
|
chunk.Chunk = byteString;
|
|
await responseStream.WriteAsync(chunk).ConfigureAwait(false);
|
|
}
|
|
}
|
|
}
|