public async Task OperationStream(IAsyncStreamReader<ServiceRequest> requestStream, IServerStreamWriter<ServiceResponse> responseStream, ServerCallContext context) { while (await requestStream.MoveNext(CancellationToken.None)) { await responseStream.WriteAsync(new ServiceResponse { Id = requestStream.Current.Id }); } }
public override async Task ServerReflectionInfo(IAsyncStreamReader<ServerReflectionRequest> requestStream, IServerStreamWriter<ServerReflectionResponse> responseStream, ServerCallContext context) { while (await requestStream.MoveNext()) { var response = ProcessRequest(requestStream.Current); await responseStream.WriteAsync(response); } }
public async Task<PersonListResponse> CreatePeople(IAsyncStreamReader<Person> requestStream, ServerCallContext context) { LogRpc(context); while (await requestStream.MoveNext(CancellationToken.None)) { var person = requestStream.Current; _personRepository.TryCreate(person); } return new PersonListResponse { People = { _personRepository.GetAllPeople() } }; }
public async Task RunClient(IAsyncStreamReader<ClientArgs> requestStream, IServerStreamWriter<ClientStatus> responseStream, ServerCallContext context) { Grpc.Core.Utils.Preconditions.CheckState(await requestStream.MoveNext()); var clientConfig = requestStream.Current.Setup; var runner = ClientRunners.CreateStarted(clientConfig); await responseStream.WriteAsync(new ClientStatus { Stats = runner.GetStats(false) }); while (await requestStream.MoveNext()) { var reset = requestStream.Current.Mark.Reset; await responseStream.WriteAsync(new ClientStatus { Stats = runner.GetStats(reset) }); } await runner.StopAsync(); }
public async Task<ChatMessageCollection> GetChatHistory(IAsyncStreamReader<ChatMessageRequest> requestStream, ServerCallContext context) { Log(context); var responses = new List<ChatMessage>(); // Async enumerator while (await requestStream.MoveNext(CancellationToken.None)) { ChatMessageRequest chatMessageRequest = requestStream.Current; ICollection<ChatMessage> chatMessages = await _chatMessageRepository.GetAccountChatHistoryAsync(chatMessageRequest.AccountId); responses.AddRange(chatMessages); } return new ChatMessageCollection { ChatMessages = { responses } }; }
public override async Task RunServer(IAsyncStreamReader<ServerArgs> requestStream, IServerStreamWriter<ServerStatus> responseStream, ServerCallContext context) { GrpcPreconditions.CheckState(await requestStream.MoveNext()); var serverConfig = requestStream.Current.Setup; var runner = ServerRunners.CreateStarted(serverConfig); await responseStream.WriteAsync(new ServerStatus { Stats = runner.GetStats(false), Port = runner.BoundPort, Cores = Environment.ProcessorCount, }); while (await requestStream.MoveNext()) { var reset = requestStream.Current.Mark.Reset; await responseStream.WriteAsync(new ServerStatus { Stats = runner.GetStats(reset) }); } await runner.StopAsync(); }
/// <summary>IAsyncStreamReader Methods.</summary> public async Task <bool> MoveNext(CancellationToken cancellationToken = default(CancellationToken)) { if (await innerReader.MoveNext(cancellationToken)) { var data = innerReader.Current; logger.ReadFromStream(context, data, typeof(TRequest), false); this.Current = MessagePackSerializer.Deserialize <TRequest>(data, context.SerializerOptions); return(true); } else { logger.ReadFromStream(context, emptyBytes, typeof(Nil), true); return(false); } }
// Client streaming public override async Task <LongGreetResponse> LongGreet(IAsyncStreamReader <LongGreetRequest> requestStream, ServerCallContext context) { string result = ""; // en este caso esta retornando una respuesta unicamente cuando se terminan los mensajes del cliente, sin embargo la respuesta se puede retornar en cualquiem moment while (await requestStream.MoveNext()) { result += string.Format("Hello {0} {1} {2}", requestStream.Current.Greeting.FirstName, requestStream.Current.Greeting.LastName, Environment.NewLine); } return(new LongGreetResponse() { Result = result }); }
// BIDi streaming public override async Task GreatEveryone(IAsyncStreamReader <GreetEveryoneRequest> requestStream, IServerStreamWriter <GreetEveryoneResponse> responseStream, ServerCallContext context) { while (await requestStream.MoveNext()) { var result = string.Format("Hellow {0}, {1}", requestStream.Current.Greeting.FirstName, requestStream.Current.Greeting.LastName); Console.WriteLine("Sending: " + result); await responseStream.WriteAsync(new GreetEveryoneResponse() { Result = result }); } }
public override async Task EventStream(IAsyncStreamReader <TransportMessage> requestStream, IServerStreamWriter <TransportMessage> responseStream, ServerCallContext context) { LogContext.SetCurrentIfNull(_hostConfiguration.LogContext); try { var ready = await requestStream.MoveNext(CancellationToken.None).OrCanceled(context.CancellationToken).ConfigureAwait(false); if (ready) { var message = requestStream.Current; if (message.ContentCase == TransportMessage.ContentOneofCase.Join) { var joinNode = message.Join.Node; var nodeAddress = new Uri(joinNode.Address); Guid.TryParse(joinNode.SessionId, out var sessionId); var nodeContext = new ServerNodeContext(context, nodeAddress, sessionId, joinNode.Host); nodeContext.LogReceived(message); var node = _collection.GetNode(nodeContext); node.Join(nodeContext, joinNode.Topology); await node.SendWelcome(_transportProvider.HostNode).ConfigureAwait(false); await node.Connect(responseStream, requestStream, context.CancellationToken).ConfigureAwait(false); nodeContext.LogDisconnect(); } } else { LogContext.Warning?.Log("GRPC no content received: {Address}", context.Peer); } } catch (OperationCanceledException) { } catch (Exception exception) { LogContext.Error?.Log(exception, "Connection {NodeAddress} faulted", context.Peer); } }
/// <summary> /// SearchPlayer_ClientStream /// </summary> public async override Task <PlayerSearchResponse> SearchPlayer_ClientStream(IAsyncStreamReader <PlayerSearchRequest> requestStream, ServerCallContext context) { PlayerSearchResponse response = new PlayerSearchResponse(); int initial = 1; while (await requestStream.MoveNext().ConfigureAwait(false)) { PlayerSearchRequest request = requestStream.Current; logger.Info(string.Format("[{0}] Requested {1} players.", "", request.ExpectedDataCount)); var Players = new List <Player>() { new Player { Age = 1, Name = "11", TeamCode = "11", }, new Player { Age = 2, Name = "22", TeamCode = "22", }, new Player { Age = 3, Name = "33", TeamCode = "33", } }; foreach (Player player in Players) { response.Players.Add(player); if (!response.Teams.ContainsKey(player.TeamCode)) { response.Teams.Add(player.TeamCode, new Team { Code = player.TeamCode, Country = player.TeamCode, Name = player.TeamCode }); } } initial += request.ExpectedDataCount; } return(response); }
/// <summary> /// Writes records to MariaDB /// </summary> /// <param name="requestStream"></param> /// <param name="responseStream"></param> /// <param name="context"></param> /// <returns></returns> public override async Task WriteStream(IAsyncStreamReader <Record> requestStream, IServerStreamWriter <RecordAck> responseStream, ServerCallContext context) { try { Logger.Info("Writing records to MariaDB..."); var schema = _server.WriteSettings.Schema; var inCount = 0; // get next record to publish while connected and configured while (await requestStream.MoveNext(context.CancellationToken) && _server.Connected && _server.WriteConfigured) { var record = requestStream.Current; inCount++; Logger.Debug($"Got record: {record.DataJson}"); if (_server.WriteSettings.IsReplication()) { var config = JsonConvert.DeserializeObject <ConfigureReplicationFormData>(_server.WriteSettings.Replication .SettingsJson); // send record to source system // add await for unit testing // removed to allow multiple to run at the same time Task.Run(async() => await Replication.WriteRecord(_connectionFactory, schema, record, config, responseStream), context.CancellationToken); } else { // send record to source system // add await for unit testing // removed to allow multiple to run at the same time Task.Run(async() => await Write.WriteRecordAsync(_connectionFactory, schema, record, responseStream), context.CancellationToken); } } Logger.Info($"Wrote {inCount} records to MariaDB."); } catch (Exception e) { Logger.Error(e, e.Message, context); } }
private Row GetParameter(IAsyncStreamReader <BundledRows> requestStream) { try { if (requestStream.MoveNext().Result == false) { logger.Debug("The Request has no parameters."); } return(requestStream?.Current?.Rows?.FirstOrDefault() ?? null); } catch { return(null); } }
public override async Task GetAssets(IAsyncStreamReader <AssetRequest> requestStream, IServerStreamWriter <AssetResponse> responseStream, ServerCallContext context) { while (await requestStream.MoveNext()) { var currentRequest = requestStream.Current; prevRequests.Add(currentRequest); var response = new AssetResponse() { AssetId = currentRequest.Id, Content = Google.Protobuf.ByteString.CopyFrom(FileManager.Assets[currentRequest.Id]) }; await responseStream.WriteAsync(response); } }
public override async Task <AverageResponse> Average(IAsyncStreamReader <AverageRequest> requestStream, ServerCallContext context) { var result = 0.0; var count = 0; while (await requestStream.MoveNext()) { result += requestStream.Current.Number.A; count++; } return(new AverageResponse() { Result = result / count }); }
public override async Task FindMaximum(IAsyncStreamReader <FindMaxRequest> requestStream, IServerStreamWriter <FindMaxResponse> responseStream, ServerCallContext context) { int max = default; while (await requestStream.MoveNext()) { if (requestStream.Current.InputNumber > max) { max = requestStream.Current.InputNumber; await responseStream.WriteAsync(new FindMaxResponse() { Max = max }); } } }
public override async Task <HelloReply> ClientStreaming(IAsyncStreamReader <StreamRequest> requestStream, ServerCallContext context) { var list = new List <List <StreamRequest> >(); while (await requestStream.MoveNext()) { var temp = requestStream.Current; list.Add(new List <StreamRequest>(Enumerable.Repeat(temp, temp.Count))); } return(new HelloReply { Message = string.Join('\n', list.Select(x => string.Join(',', x.Select(y => y.Message)))) }); }
public override async Task <AverageResponse> ComputeAverage(IAsyncStreamReader <AverageRequest> requestStream, ServerCallContext context) { int total = 0; double result = 0.0; while (await requestStream.MoveNext()) { result += requestStream.Current.Number; total++; } return(new AverageResponse() { Result = result / total }); }
public override async Task <ComputeAverageResponse> ComputeAverage(IAsyncStreamReader <ComputeAverageRequest> requestStream, ServerCallContext context) { double result; int count = 0, sum = 0; while (await requestStream.MoveNext()) { sum += requestStream.Current.Number; count++; } result = (double)sum / count; return(new ComputeAverageResponse() { Result = result }); }
public async Task <bool> MoveNext(CancellationToken cancellationToken) { try { return(await _wrappedReader.MoveNext(cancellationToken)); } catch (RpcException ex) { if (RpcExceptionBuilder.Build(ex, out var rpcException)) { throw rpcException; } throw; } }
public override async Task <AddMultipleProductsToCartResponse> AddMultipleProductsToCart(IAsyncStreamReader <AddMultipleProductsToCartRequest> requestStream, ServerCallContext context) { int counter = 0; while (await requestStream.MoveNext()) { var prosuct = AddToCartDB(requestStream.Current.Product); Console.WriteLine("product Added!"); counter++; } return(new AddMultipleProductsToCartResponse { Status = counter }); }
public override async Task MaxHeartRate(IAsyncStreamReader <MaxHeartRateRequest> requestStream, IServerStreamWriter <MaxHeartRateResponse> responseStream, ServerCallContext context) { int?max = null; while (await requestStream.MoveNext()) { if (max == null || max < requestStream.Current.Number) { max = requestStream.Current.Number; await responseStream.WriteAsync(new MaxHeartRateResponse() { Maximum = max.Value }); } } }
public override async Task <SleepAverageResponse> SleepAverage(IAsyncStreamReader <SleepAverageRequest> requestStream, ServerCallContext context) { int total = 0; double average = 0.0; while (await requestStream.MoveNext()) { average += requestStream.Current.Number; total++; } return(new SleepAverageResponse() { Average = average / total }); }
/// <summary> /// BiDirectional streaming /// </summary> /// <param name="requestStream"></param> /// <param name="responseStream"></param> /// <param name="context"></param> /// <returns></returns> public override async Task SaveAll(IAsyncStreamReader <EmployeeRequest> requestStream, IServerStreamWriter <EmployeeResponse> responseStream, ServerCallContext context) { while (await requestStream.MoveNext()) { var employee = requestStream.Current.Employee; lock (this) { Employees.employees.Add(employee); } await responseStream.WriteAsync(new EmployeeResponse { Employee = employee }); } }
public static async Task ReadResponseAsync(IAsyncStreamReader <HelloMessage.HelloMessageResponse> responseStream) { Console.WriteLine("start recevied message"); while (await responseStream.MoveNext()) { var message = responseStream.Current; Console.WriteLine("recevied message" + message); Console.WriteLine(message); } //await foreach (var message in responseStream.ReadAllAsync()) //{ // Console.WriteLine("recevied message" + message); // Console.WriteLine(message); //} //Console.WriteLine("complete"); }
internal static async Task WaitForServerStreamExceptionAsync <THeader, TResult>( IAsyncStreamReader <Message <TResult> > responseStream, Metadata?responseHeaders, Marshaller <THeader> marshaller, CancellationToken token) { // here should throw the RpcException from server-side // see ExceptionHandlingTestBase ThrowApplicationExceptionServerStreamingHeader and ThrowApplicationExceptionDuplexStreamingHeader await responseStream.MoveNext(token).ConfigureAwait(false); // this line should not be reached // if the case, check for the headers content CompatibilityTools.DeserializeMethodOutputHeader(marshaller, responseHeaders); throw new InvalidOperationException("The server streaming ResponseHeadersAsync did not provide any headers, headers are available only after the streaming."); }
public override async Task <BlankResponse> ReadingsStream(IAsyncStreamReader <SensorReadings> requestStream, ServerCallContext context) { logger.LogInformation("\r\n"); while (await requestStream.MoveNext()) { foreach (var readingValue in requestStream.Current.ReadingValues) { logger.LogInformation($"{requestStream.Current.SensorId} | {readingValue.Field} : {readingValue.Value}"); } } logger.LogInformation("\r\n"); return(await Task.FromResult(new BlankResponse { })); }
private IObservable <double> ConnectToOperationsPerMinuteStream() { IAsyncStreamReader <LoadResponse> asyncStreamReader = _client.ReadCalculatorLoad(new LoadIntervalRequest { IntervalInSeconds = 1 }).ResponseStream; return(Observable.Create <double>(async observer => { while (await asyncStreamReader.MoveNext()) { observer.OnNext(asyncStreamReader.Current.InvocationsPerMinutes); } observer.OnCompleted(); })); }
static IObservable <Unit> RecursiveActionAsync <T>(IAsyncStreamReader <T> stream, Func <T, IObservable <Unit> > asyncAction) { return(stream.MoveNext().ContinueWith(x => { if (x) { return asyncAction(stream.Current) .ContinueWith(_ => RecursiveActionAsync(stream, asyncAction)); } else { stream.Dispose(); return Observable.ReturnUnit(); } })); }
public override async Task GetCustomersBiDirectionalStream(IAsyncStreamReader <CustomerRequest> requestStream, IServerStreamWriter <CustomerResponse> responseStream, ServerCallContext context) { Console.WriteLine("Started"); while (await requestStream.MoveNext() && !context.CancellationToken.IsCancellationRequested) { CustomerRequest request = requestStream.Current; CustomerResponse customer = customerList.FirstOrDefault(customer => customer.Id == request.CustomerId); await responseStream.WriteAsync(customer); await Task.Delay(TimeSpan.FromSeconds(5)); Console.WriteLine("Keeping on"); //Dikkat return yok } Console.WriteLine("Finished"); }
static async void ReceiveEvents(IAsyncStreamReader <EventLog> stream, CancellationToken token) { Console.WriteLine("Start receiving real-time events"); try { while (await stream.MoveNext(token)) { var eventLog = stream.Current; Console.WriteLine("Event: {0}", eventLog); } } catch (Exception e) { Console.WriteLine("Monitoring error: {0}", e); } finally { Console.WriteLine("Stop receiving real-time events"); } }
//CLIENT SREAMING public override async Task <LongGreetResponse> LongGreet(IAsyncStreamReader <LongGreetRequest> requestStream, ServerCallContext context) { string result = ""; while (await requestStream.MoveNext()) { result += String.Format("Hello {0} {1} {2}", requestStream.Current.Greeting.FirstName, requestStream.Current.Greeting.LastName, Environment.NewLine); } return(new LongGreetResponse() { Result = result }); }
public override async Task Analyse(IAsyncStreamReader <Msg> requestStream, IServerStreamWriter <Msg> responseStream, ServerCallContext context) { try { while (await requestStream.MoveNext()) { await responseStream.WriteAsync(requestStream.Current); } } catch (IOException) { Console.WriteLine("Exit connection Stream"); } }
public async Task Chat(IAsyncStreamReader<ChatMessage> requestStream, IServerStreamWriter<ChatMessage> responseStream, ServerCallContext context) { Log(context); Program.Log("Server starting to chat"); while (await requestStream.MoveNext()) { ChatMessage clientChatMessage = requestStream.Current; Program.Log($"Client says {clientChatMessage}"); ChatMessage serverChatMessage = Utility.GetRandomChatMessage(0); await responseStream.WriteAsync(serverChatMessage); } // Returning from the method will automatically complete the response async enumerator on the client. }
private async Task <(long chunks, long bytes)> StreamContentAsync(Stream targetStream, IAsyncStreamReader <CopyFileResponse> replyStream, CopyToOptions?options, CancellationToken ct) { long chunks = 0L; long bytes = 0L; while (await replyStream.MoveNext(ct)) { chunks++; CopyFileResponse reply = replyStream.Current; bytes += reply.Content.Length; reply.Content.WriteTo(targetStream); options?.UpdateTotalBytesCopied(bytes); } return(chunks, bytes); }
async Task ConvertToColumnar(ParameterData[] Parameters, IAsyncStreamReader <global::Qlik.Sse.BundledRows> requestStream) { int rowNum = 0; while (await requestStream.MoveNext()) { var bundledRows = requestStream.Current; var nrOfRows = bundledRows.Rows.Count; for (int r = 0; r < nrOfRows; r++) { var Row = bundledRows.Rows[r]; var logRowData = new List <string>(); for (int i = 0; i < Parameters.Length; i++) { var param = Parameters[i]; var dual = Row.Duals[i]; switch (param.DataType) { case DataType.Numeric: param.Numerics.Add(dual.NumData); logRowData.Add($"{dual.NumData}"); break; case DataType.String: param.Strings.Add(dual.StrData); logRowData.Add($"{dual.StrData}"); break; case DataType.Dual: // Dual not supported by R take numerical value param.Numerics.Add(dual.NumData); logRowData.Add($"{dual.NumData}"); break; } } if (logger.IsTraceEnabled) { var logRowDataStr = String.Join(", ", logRowData); logger.Trace("Incoming data row[{0}]: {1}", rowNum, logRowDataStr); rowNum++; } } } }
private async Task OnSendConfig(IAsyncStreamReader<CurrentLibraryConfig> requestStream, IServerStreamWriter<UpdatedLibraryConfig> responseStream, ServerCallContext context) { if (this.onConfigReceived == null) { return; } try { while (await requestStream.MoveNext(this.cts.Token).ConfigureAwait(false)) { CurrentLibraryConfig configRequest = requestStream.Current; try { var configResponse = this.onConfigReceived(configRequest, context); if (configRequest.Config == null || !configRequest.Config.Equals(configResponse.Config)) { await responseStream.WriteAsync(configResponse) .ConfigureAwait(false); } Interlocked.Increment(ref this.stats.ConfigsReceived); } catch (System.Exception e) { // unexpected exception occured while processing the config request Interlocked.Increment(ref this.stats.ConfigsFailed); Diagnostics.LogError(FormattableString.Invariant($"Unknown exception while processing a config request through the OpenCensus gRpc input. {e.ToString()}")); } } } catch (TaskCanceledException) { // we have been stopped } catch (System.Exception e) { // unexpected exception occured Diagnostics.LogError(FormattableString.Invariant($"Unknown exception while reading config from gRpc stream. {e.ToString()}")); this.Stop(); } }
/// <summary> /// Receives a stream of message/location pairs, and responds with a stream of all previous /// messages at each of those locations. /// </summary> public override async Task RouteChat(IAsyncStreamReader<RouteNote> requestStream, IServerStreamWriter<RouteNote> responseStream, ServerCallContext context) { while (await requestStream.MoveNext()) { var note = requestStream.Current; List<RouteNote> prevNotes = AddNoteForLocation(note.Location, note); foreach (var prevNote in prevNotes) { await responseStream.WriteAsync(prevNote); } } }
/// <summary> /// Gets a stream of points, and responds with statistics about the "trip": number of points, /// number of known features visited, total distance traveled, and total time spent. /// </summary> public override async Task<RouteSummary> RecordRoute(IAsyncStreamReader<Point> requestStream, ServerCallContext context) { int pointCount = 0; int featureCount = 0; int distance = 0; Point previous = null; var stopwatch = new Stopwatch(); stopwatch.Start(); while (await requestStream.MoveNext()) { var point = requestStream.Current; pointCount++; if (CheckFeature(point).Exists()) { featureCount++; } if (previous != null) { distance += (int) previous.GetDistance(point); } previous = point; } stopwatch.Stop(); return new RouteSummary { PointCount = pointCount, FeatureCount = featureCount, Distance = distance, ElapsedTime = (int)(stopwatch.ElapsedMilliseconds / 1000) }; }