public override async Task <GatherResponse> Gather(IAsyncStreamReader <GatherRequest> requestStream, ServerCallContext context) { ICollection <string> messages = new List <string>(); await foreach (GatherRequest request in requestStream.ReadAllAsync()) { messages.Add(request.Msg); } GatherResponse response = new() { Result = string.Join(" - ", messages) }; return(response); } }
public override async Task <CounterReply> AccumulateCount(IAsyncStreamReader <CounterRequest> requestStream, ServerCallContext context) { using (var call = _counterClient.AccumulateCount()) { await foreach (var message in requestStream.ReadAllAsync()) { await call.RequestStream.WriteAsync(message); } await call.RequestStream.CompleteAsync(); return(await call); } }
public override async Task <HelloReply> SayHelloClientStreaming(IAsyncStreamReader <HelloRequest> requestStream, ServerCallContext context) { var names = new List <string>(); await foreach (var request in requestStream.ReadAllAsync()) { names.Add(request.Name); } return(new HelloReply() { Message = string.Join(",", names) }); }
public async Task <SentenceMessage> RunAsync(IAsyncStreamReader <WordMessage> request, ServerCallContext context) { List <string> words = new List <string>(); await foreach (var word in request.ReadAllAsync()) { words.Add(word.Word); Console.WriteLine($"Received word: {word.Word}"); } return(new SentenceMessage { Sentence = string.Join(" ", words) + "." }); }
public override async Task <Empty> SendDiagnostics(IAsyncStreamReader <ReadingMessage> requestStream, ServerCallContext context) { var theTask = Task.Run(async() => { await foreach (var reading in requestStream.ReadAllAsync()) { _logger.LogInformation($"Received reading: {reading}"); } }); await theTask; return(new Empty()); }
public override async Task <NumberResponse> SendNumber(IAsyncStreamReader <NumberRequest> requestStream, ServerCallContext context) { var total = 0; await foreach (var number in requestStream.ReadAllAsync()) { _logger.LogInformation($"Recieved number -> {number.Value}"); total += number.Value; } return(new NumberResponse { Result = total }); }
public override async Task <HelloReply> SayHelloToLastRequest(IAsyncStreamReader <HelloRequest> requestStream, ServerCallContext context) { var name = string.Empty; await foreach (var request in requestStream.ReadAllAsync()) { name = request.Name; } return(new HelloReply { Message = $"Hello {name}" }); }
public override async Task StreamingBothWays(IAsyncStreamReader <HelloRequest> requestStream, IServerStreamWriter <HelloReply> responseStream, ServerCallContext context) { var readTask = Task.Run(async() => { _logger.LogInformation($"Request Header:"); foreach (var header in context.RequestHeaders) { _logger.LogInformation($" {header.Key} = {header.Value}"); } try { await foreach (var message in requestStream.ReadAllAsync(context.CancellationToken)) { await responseStream.WriteAsync(new HelloReply() { Message = "Echo Duplex " + message.Name, }); } } catch (TaskCanceledException tex) { // client disconnected while command executing } catch (System.IO.IOException iex) { // client disconnected } }); try { while (!readTask.IsCompleted) { await responseStream.WriteAsync(new HelloReply() { Message = "Duplex", }); await Task.Delay(TimeSpan.FromMilliseconds(500), context.CancellationToken); } } catch (TaskCanceledException tex) { // client disconnected while command executing } await readTask; }
public override async Task <HelloReply> SayHelloClientStreaming(IAsyncStreamReader <HelloRequest> requestStream, ServerCallContext context) { var names = new List <string>(); await foreach (var message in requestStream.ReadAllAsync()) { _logger.LogInformation($"SayHelloClientStreaming: accumulating name {message.Name}."); names.Add(message.Name); } _logger.LogInformation($"SayHelloClientStreaming: sending greeting to {string.Join(", ", names)}"); return(new HelloReply { Message = "Hello " + string.Join(", ", names) }); }
public override async Task Download(IAsyncStreamReader <ImageRequest> requestStream, IServerStreamWriter <ImageResponse> responseStream, ServerCallContext context) { var readTask = Task.Run(async() => { await foreach (var message in requestStream.ReadAllAsync()) { _queue.Enqueue(message.Url); _logger.LogInformation($"Download request {message.Url}"); } }); await readTask.ConfigureAwait(false); await ProcessQueue(responseStream, context).ConfigureAwait(false); }
private async Task ConsumeMessagesAsync(IServerChatClient client, IAsyncStreamReader <ClientMessage> requestStream, CancellationToken token) { await foreach (var message in requestStream.ReadAllAsync(token).ConfigureAwait(false)) { try { await client.HandleMessageAsync(message, _clientRepository).ConfigureAwait(false); } catch (Exception e) { Log.Error(nameof(GrpcChatService), $"Something went wrong while broadcasting a message: {e.InnerException?.Message}"); throw; } } }
public async override Task <VoucherResponse> UploadVoucher(IAsyncStreamReader <VoucherRequest> requestStream, ServerCallContext context) { VoucherResponse response = new VoucherResponse { Message = "Operation Successful" }; await foreach (var m in requestStream.ReadAllAsync()) { _tripVoucherService.UploadVoucher(new TripVoucher { Amount = m.Amount, }); } return(response); }
//Client stream public override async Task <BrojMsg> Sabirac(IAsyncStreamReader <BrojMsg> requestStream, ServerCallContext context) { _log.LogDebug("Krecem sa radom"); int zbir = 0; await foreach (BrojMsg br in requestStream.ReadAllAsync()) { _log.LogDebug($"Primio {br.Br}"); zbir += br.Br; } _log.LogDebug("Zavrsen stream, vracam rezultat"); return(new BrojMsg { Br = zbir }); }
public override async Task <BrojPoruka> Sabirac(IAsyncStreamReader <BrojPoruka> requestStream, ServerCallContext context) { int zbir = 0; _logger.LogInformation("Primam stream"); await foreach (BrojPoruka bp in requestStream.ReadAllAsync()) { _logger.LogInformation($"Dobio broj {bp.Br}"); zbir += bp.Br; } _logger.LogInformation("Zavrsen stream, saljem odgovor"); return(new BrojPoruka { Br = zbir }); }
public override async Task <HelloReply> SayHellos(IAsyncStreamReader <HelloRequest> requestStream, ServerCallContext context) { List <string> names = new List <string>(); await foreach (var item in requestStream.ReadAllAsync()) { Console.WriteLine($"Server Read {item} "); names.Add(item.Name); } return(new HelloReply { Message = string.Join(",", names) }); }
// client streaming public override async Task <HelloReply> StreamingFromClient(IAsyncStreamReader <HelloRequest> requestStream, ServerCallContext context) { var overallMessage = "Hello "; await foreach (var message in requestStream.ReadAllAsync()) { // process individual message; overallMessage += $"{message.Name}"; Console.Write(message.Name); } return(new HelloReply { Message = overallMessage }); // reply only sent when client ends stream }
public override async Task <InsertBulkProductResponse> InsertBulkProduct(IAsyncStreamReader <ProductModel> requestStream, ServerCallContext context) { await foreach (var requestData in requestStream.ReadAllAsync()) { _productsContext.Product.Add(_mapper.Map <Product>(requestData)); } var insertCount = await _productsContext.SaveChangesAsync(); return(new InsertBulkProductResponse { Success = insertCount > 0, InsertCount = insertCount }); }
public override async Task DonateKittens(IAsyncStreamReader <LitterOfKittens> litters, IServerStreamWriter <CeaseAndDesist> responses, ServerCallContext _) { await foreach (var litter in litters.ReadAllAsync()) { foreach (var kitten in litter.Kittens) { _basket.AddKitten(kitten); } if (_basket.TooManyKittens()) { await responses.WriteAsync(new CeaseAndDesist { Severity = 100, Message = "Please stop donating kittens" }); } } }
private static async Task <List <Permission> > GetPermissions(IAsyncStreamReader <PermissionRequest> requestStream) { var permissions = new List <Permission>(); await foreach (var permission in requestStream.ReadAllAsync()) { permissions.Add(new Permission { UserId = permission.UserId, UserPermission = (UserPermission)permission.Permission }); } return(permissions); }
public override async Task <HelloReply> SayHelloToLotsOfBuddies(IAsyncStreamReader <HelloRequest> requestStream, ServerCallContext context) { var names = new List <string>(); await foreach (var request in requestStream.ReadAllAsync()) { names.Add(request.Name); } var message = $"Hello {string.Join(", ", names)}"; _logger.LogInformation($"Sending greeting {message}."); return(new HelloReply { Message = message }); }
public override async Task <CounterReply> AccumulateCount(IAsyncStreamReader <CounterRequest> requestStream, ServerCallContext context) { var httpContext = context.GetHttpContext(); _logger.LogInformation($"Connection id: { httpContext.Connection.Id}"); await foreach (var message in requestStream.ReadAllAsync()) { _logger.LogInformation($"Incrementing count by {message.Count}"); _counter.Increment(message.Count); } return(new CounterReply { Count = _counter.Count }); }
// 可以支持更复杂的方案,例如同时读取请求和发送响应 public override async Task ClientServerStream( IAsyncStreamReader <HelloRequest> requestStream, IServerStreamWriter <HelloReply> responseStream, ServerCallContext context) { var counter = 0; await foreach (var message in requestStream.ReadAllAsync()) { counter++; await responseStream.WriteAsync(new() { Message = message + " " + counter }); } }
public async override Task GetWeatherForecastByDateStream(IAsyncStreamReader <WeatherForecastByDateRequest> requestStream, IServerStreamWriter <WeatherForecast> responseStream, ServerCallContext context) { await foreach (var request in requestStream.ReadAllAsync()) { if (context.CancellationToken.IsCancellationRequested) { break; } await Task.Delay(request.Delay.ToTimeSpan()); var response = _weatherForecastGenerator.GenerateWeatherForecast(request.Date); await responseStream.WriteAsync(response); _logger.LogInformation($"weather forecast sent on {request.Date:dd:MM:yyyy}"); } }
public override async Task <SimpleResponse> StreamingFromClient(IAsyncStreamReader <SimpleRequest> requestStream, ServerCallContext context) { SimpleRequest?lastRequest = null; await foreach (var item in requestStream.ReadAllAsync()) { lastRequest = item; } ; if (lastRequest == null) { throw new InvalidOperationException("No client requests received."); } return(CreateResponse(lastRequest)); }
public override async Task BidiHello ( IAsyncStreamReader <HelloRequest> requestStream, IServerStreamWriter <HelloReply> responseStream, ServerCallContext context ) { await foreach (var request in requestStream.ReadAllAsync()) { var helloReply = new HelloReply { Message = "Hello " + request.Name }; await responseStream.WriteAsync(helloReply); } }
public override async Task <Empty> MetricsUpdate(IAsyncStreamReader <MetricsUpdateRequest> requestStream, ServerCallContext context) { try { await foreach (var message in requestStream.ReadAllAsync()) { _logger.LogInformation("Got metrics update"); } } catch (System.IO.IOException) { // This means the server shut down really fast, without closing connection. _logger.LogInformation($"Server with trace {context.GetHttpContext().TraceIdentifier} lost connection down unexpectedly"); } return(new Empty()); }
public override async Task Start(IAsyncStreamReader <GameRequest> requestStream, IServerStreamWriter <GameResponse> responseStream, ServerCallContext context) { await foreach (var item in requestStream.ReadAllAsync()) { if (item.EndGame) { break; } // // client has played its dice // var serverResult = await RollDice(); await responseStream.WriteAsync(new GameResponse { ServerResult = $"Server result: {serverResult}" }); } }
public override async Task HalfDuplexEcho(IAsyncStreamReader <EchoRequest> requestStream, IServerStreamWriter <EchoResponse> responseStream, ServerCallContext context) { var messages = new List <string>(); await foreach (var message in requestStream.ReadAllAsync()) { messages.Add(message.Message); } foreach (var message in messages) { await responseStream.WriteAsync(new EchoResponse { Message = message }); } }
public override async Task MailBox(IAsyncStreamReader <ForwardMailMessage> requestStream, IServerStreamWriter <MailBoxMessage> responseStream, ServerCallContext context) { var mailboxName = context.RequestHeaders.Single(c => c.Key == "mailbox-name").Value; _logger.LogInformation($"Connected to {mailboxName}"); _mailQueue.Changed += _mailQueue_Changed; _mailQueue.Received(); try { await foreach (var item in requestStream.ReadAllAsync()) { if (_mailQueue.TryForwardMail(out var message)) { _logger.LogInformation($"Forwarded mail: {message.Content}"); } else { _logger.LogWarning("No mail to forward."); } } } finally { _mailQueue.Changed -= _mailQueue_Changed; } _logger.LogInformation($"{mailboxName } disconnected"); await Task.CompletedTask; async Task _mailQueue_Changed((int totalCount, int fowardCount, Reason reason) state) { await responseStream.WriteAsync(new MailBoxMessage { Forwarded = state.totalCount, New = state.totalCount - state.fowardCount, Reason = state.reason }); } }
public override async Task SayHelloEcho(IAsyncStreamReader <HelloEcho> requestStream, IServerStreamWriter <HelloEcho> responseStream, ServerCallContext context) { var rnd = new Random(); while (!context.CancellationToken.IsCancellationRequested) { await foreach (var request in requestStream.ReadAllAsync()) { // Gotta look busy await Task.Delay(rnd.Next(1000)); await responseStream.WriteAsync(new HelloEcho { Message = $"Echoed from server: {request.Message}" }); } } }