public static async Task <Channel> ConnectAsync(this GrpcHostOptions options, CancellationToken token)
        {
            string host = "localhost";

            if (options.Host.HasValue())
            {
                host = options.Host.Value();
            }

            int port = 50051;

            if (options.Port.HasValue())
            {
                // try to parse the value
                if (!int.TryParse(options.Port.Value(), out port))
                {
                    throw new ArgumentException("Port not in range of [1..65535]");
                }
                else if (port < 1 || port > ushort.MaxValue)
                {
                    throw new ArgumentException("Port not in range of [1..65535]");
                }
            }

            var channel = new Channel(host, port, ChannelCredentials.Insecure, new[]
            {
                new ChannelOption(ChannelOptions.MaxReceiveMessageLength, int.MaxValue),
            });

            Console.WriteLine($"Connecting to grpc host {channel.Target} ..");
            var connectTask = channel
                              .ConnectAsync();
            var cancellationTask = token
                                   .AwaitCancellationAsync();
            var completedTask = await Task
                                .WhenAny(connectTask, cancellationTask)
                                .ConfigureAwait(false);

            if (completedTask == cancellationTask)
            {
                if (token.IsCancellationRequested)
                {
                    throw new OperationCanceledException();
                }
                else
                {
                    // this is a bug
                    throw new InvalidOperationException();
                }
            }

            // await the connect task
            try
            {
                await connectTask;

                Console.WriteLine($"Connection established to grpc host {channel.Target}");
                return(channel);
            }
            catch (Exception ex)
            {
                throw new InvalidOperationException($"Could not connect to grpc host {channel.Target}", ex);
            }
        }
示例#2
0
        public async Task RunAsync(CancellationToken token)
        {
            int chunkSize = 1024 * 1024;

            if (Options.ChunkSize.HasValue())
            {
                chunkSize = Convert.ToInt32(Options.ChunkSize.Value());
            }

            long totalChunks = 1000;

            if (Options.TotalChunks.HasValue())
            {
                totalChunks = Convert.ToInt64(Options.TotalChunks.Value());
            }

            using (var cancellationTokenSource = new CancellationTokenSource())
            {
                var connectTask = Options
                                  .GrpcHost
                                  .ConnectAsync(cancellationTokenSource.Token);
                var cancellationTask = token.AwaitCancellationAsync();
                var completedTask    = await Task.WhenAny(connectTask, cancellationTask).ConfigureAwait(false);

                if (completedTask == cancellationTask)
                {
                    // operation cancelled
                    return;
                }

                var channel = await connectTask.ConfigureAwait(false);

                var streamingService = new StreamingService.StreamingServiceClient(channel);
                var streamBytesCall  = streamingService.StreamBytes(new StreamBytesRequest()
                {
                    ChunkSize   = chunkSize,
                    TotalChunks = totalChunks,
                }, default);

                var  stopwatch  = Stopwatch.StartNew();
                long totalBytes = 0;
                try
                {
                    await streamBytesCall
                    .SelectAsync(streamBytesResponse =>
                    {
                        totalBytes += streamBytesResponse.Chunk.Length;
                    }, token)
                    .ConfigureAwait(false);
                }
                catch (Exception)
                {
                    if (token.IsCancellationRequested)
                    {
                        // cancelled by user
                    }
                    else
                    {
                        throw;
                    }
                }
                finally
                {
                    Console.WriteLine($"Transferred {totalBytes} bytes in {stopwatch.Elapsed.TotalMilliseconds}ms ({(totalBytes / (1024 * 1024) / stopwatch.Elapsed.TotalSeconds)} MBytes/second)");
                }
            }
        }